java操作远程共享目录

一.前言

     根据客户反馈,在进行文件下载的时候,新增远程共享目录,下载对应的文件到远程共享目录,采用常用的IO操作模式,提示下载成功,但是客户去远程共享目录查看对应的下载文件,反馈说没有找到对应的文件。要求系统需要支持上传远程共享目录,为什么有一个这样的需求?由于下载的文件涉及到了支付文件,里面的金额不允许进行修改,如果放在本地路径有可能会不会出现人为的修改,一般涉及到钱的问题,客户都是比较谨慎的,刚好没有接触过操作远程共享目录的,就google了一下看有没有对应的操作说明,下面简单总结一下。

二.远程共享目录操作

1、需要下载对应的jcifs-1.3.18.jar,本例子采用3.18版本的,下载链接:https://jcifs.samba.org/

2、涉及的主要类是  SmbFile(远程文件操作类) ,还有就是进行登录验证,验证对应的远程目录的合法性的操作,其他操作就普通的IO流的操作。

3、从远程共享目录下载文件

/**
     * 方法说明:从远程共享目录下载文件
     * @param localDir         本地临时路径
     * @param removeDir        远程共享路径
     * @param _fileName        远程共享文件名
     * @param removeIp         远程共享目录IP
     * @param removeLoginUser  远程共享目录用户名
     * @param removeLoginPass  远程共享目录密码
     * @return
     * @throws Exception
     */
    public static int smbDownload(String localDir, String removeDir,
            String _fileName, String removeIp, String removeLoginUser,
            String removeLoginPass) throws Exception {
        InputStream in = null;
        OutputStream out = null;
        try {
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
                    removeIp, removeLoginUser, removeLoginPass);
            SmbFile remoteFile = new SmbFile(removeDir + _fileName, auth);
            if (!remoteFile.exists()) {
                return 0;
            }

            File dir = new File(localDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String fileName = _fileName.substring(_fileName.lastIndexOf("\\")+1, _fileName.length());
            File localFile = new File(localDir + fileName);
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return 1;
    }

4、上传文件都远程共享目录

/**
     * 方法说明:上传文件到远程共享目录
     * @param localDir         本地临时路径(A:/测试/测试.xls)
     * @param removeDir        远程共享路径(smb://10.169.2.xx/测试/,特殊路径只能用/)
     * @param removeIp         远程共享目录IP(10.169.2.xx)
     * @param removeLoginUser  远程共享目录用户名(user)
     * @param removeLoginPass  远程共享目录密码(password)
     * @return
     * @throws Exception   0成功/-1失败
     */
    public static int smbUploading(String localDir, String removeDir,
            String removeIp, String removeLoginUser, String removeLoginPass) throws Exception {
        NtlmPasswordAuthentication auth = null;
        OutputStream out = null;
        int retVal = 0;  
        try {
            File dir = new File(localDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            InetAddress ip = InetAddress.getByName(removeIp); 
            UniAddress address = new UniAddress(ip);
            // 权限验证
             auth = new NtlmPasswordAuthentication(removeIp, removeLoginUser, removeLoginPass);
            SmbSession.logon(address,auth); 
            
            //远程路径判断文件文件路径是否合法
            SmbFile remoteFile = new SmbFile(removeDir + dir.getName(), auth);
            remoteFile.connect();       
            if(remoteFile.isDirectory()){ 
                retVal = -1;
            }
        
            // 向远程共享目录写入文件
            out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
            out.write(toByteArray(dir));
        } catch (UnknownHostException e) {
            retVal = -1;
            e.printStackTrace();
        } catch (MalformedURLException e) {
            retVal = -1;
            e.printStackTrace();
        } catch (SmbException e) {
            retVal = -1;
            e.printStackTrace();
        } catch (IOException e) {
            retVal = -1;
            e.printStackTrace();
        } finally{
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return retVal;
    }
    
    /**
     * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
     *
     * @param file 文件
     * @return   字节数组
     * @throws IOException IO异常信息
     */
    @SuppressWarnings("resource")
    public static byte[] toByteArray(File file) throws IOException {
        FileChannel fc = null;
        try {
            fc = new RandomAccessFile(file, "r").getChannel();
            MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
                    fc.size()).load();
            byte[] result = new byte[(int) fc.size()];
            if (byteBuffer.remaining() > 0) {
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                fc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

转载于:https://www.cnblogs.com/hongwz/p/7457177.html

<think>好的,我需要帮助用户了解如何使用Java操作共享目录。用户提到了示例代码和教程,所以首先我需要回忆Java中处理文件系统操作的相关类和方法。 首先,Java标准库中处理文件的主要是java.io和java.nio包。用户提到的是共享目录,这通常指的是网络上的共享文件夹,比如通过SMB(Samba)或NFS挂载的目录。在Java中,操作这些共享目录其实和操作本地目录类似,只要系统已经将共享目录挂载到了本地路径。例如,在Linux中,NFS共享可能挂载到/mnt/nfs,这时候Java程序可以像访问本地文件一样访问该路径。 不过,如果共享目录需要身份验证,可能需要额外的处理。比如,使用JCIFS库来处理SMB协议。用户提供的引用[4]中提到了nfs_java,但标准Java库可能不支持直接访问SMB或NFS,需要第三方库。因此,我需要考虑两种情况:一种是挂载到本地路径后的普通文件操作,另一种是使用库如JCIFS直接访问。 首先,对于已挂载的共享目录Java代码和普通文件操作一样。例如,使用Files类读取或写入文件。示例代码可能包括列出目录内容、读取文件内容等。 其次,如果直接访问SMB共享,可能需要JCIFS。例如,使用SmbFile类来访问远程路径。需要添加JCIFS依赖,然后通过smb://URL进行访问,同时提供用户名和密码。 用户提供的引用[4]中的代码片段有使用nfs_java,但我不确定这个库的详细信息。可能需要查找相关资料。不过,更常见的是使用JCIFS处理SMB,或者使用NFS客户端库。但Java标准库中没有直接支持NFS的类,所以可能需要第三方库。 因此,我需要给出两种情况的示例:一种是挂载后的本地路径操作,另一种是使用JCIFS访问SMB共享。同时,提醒用户关于依赖库和配置的注意事项。 在引用方面,用户提供的引用[4]提到了访问共享目录的配置,所以需要确保代码示例符合该引用中的方法。例如,使用NFS或Samba配置后,Java程序通过挂载点访问。代码示例可能包括使用java.io.File类或NIO的Path和Files类。 总结步骤: 1. 说明共享目录的两种访问方式:挂载本地路径和使用第三方库。 2. 提供挂载后的Java文件操作示例。 3. 提供使用JCIFS访问SMB的示例。 4. 提到可能的身份验证需求和异常处理。 5. 引用用户提供的引用[4]中的相关内容,如配置和错误处理。 需要确保示例代码正确,比如使用正确的URL格式,处理IOException等。同时,注意用户可能需要添加JCIFS依赖,比如Maven中的依赖配置。 最后,生成相关问题,帮助用户深入理解,比如权限处理、性能优化等。</think>### Java操作共享目录实现方法 Java操作网络共享目录(Samba/NFS)主要有两种实现方式: #### 一、通过本地挂载点访问(推荐) 1. 先在操作系统层挂载共享目录 ```bash # Linux挂载Samba示例 sudo mount -t cifs //192.168.1.100/shared /mnt/samba -o username=user,password=pass # Linux挂载NFS示例 sudo mount -t nfs 192.168.1.100:/shared /mnt/nfs ``` 2. Java使用标准文件API操作 ```java import java.nio.file.*; public class SharedDirDemo { public static void main(String[] args) { Path sharedPath = Paths.get("/mnt/samba/demo.txt"); try { // 写入文件 Files.write(sharedPath, "Hello Samba".getBytes()); // 读取文件 byte[] data = Files.readAllBytes(sharedPath); System.out.println(new String(data)); // 列出目录 try (DirectoryStream<Path> stream = Files.newDirectoryStream(sharedPath.getParent())) { stream.forEach(System.out::println); } } catch (IOException e) { e.printStackTrace(); // 异常处理参考引用[4] } } } ``` #### 二、使用JCIFS库直接访问SMB共享(需添加依赖) ```xml <!-- Maven依赖 --> <dependency> <groupId>jcifs</groupId> <artifactId>jcifs</artifactId> <version>1.3.17</version> </dependency> ``` ```java import jcifs.smb.*; public class SmbDemo { public static void main(String[] args) { String url = "smb://user:pass@192.168.1.100/shared/demo.txt"; try { SmbFile file = new SmbFile(url); try (SmbFileOutputStream out = new SmbFileOutputStream(file)) { out.write("Test content".getBytes()); } try (SmbFileInputStream in = new SmbFileInputStream(file)) { byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { System.out.write(buffer, 0, length); } } } catch (SmbException | MalformedURLException e) { // 异常处理参考引用[4]的日志记录方式 System.err.println(this.getClass().getName() + "||" + e.getMessage()); } } } ``` ### 关键注意事项 1. 权限配置:确保操作系统账户或代码中提供的凭证有足够权限[^4] 2. 异常处理:网络操作必须捕获IOException及相关异常 3. 连接超时:建议设置合理的连接超时参数 4. 性能优化:对大文件使用缓冲流,避免内存溢出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值