Java 访问共享文件以及下载共享文件

啦啦啦啦~总结一下访问共享文件遇到什么问题~

    //从共享目录下载文件
    public static void smbFile() {
        String user = "your_user_name";
        String pass ="your_pass_word";

        String sharedFolder="shared";
        String path="smb://ip_address/"+sharedFolder+"/myfile.jar";
        InputStream in = null ;
        OutputStream out = null;
        String fileName = null;
        try {
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",user, pass);
            SmbFile remoteFile = new SmbFile(path,auth);
            remoteFile.connect(); //尝试连接

            //创建文件流
            fileName = "your_file";
            File localFile = new File(fileName);

            if (!localFile.exists()) {
                localFile.createNewFile();
            }

            in = new BufferedInputStream(new SmbFileInputStream(path));
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] buffer = new byte[1024];
            while(in.read(buffer)!=-1){
                out.write(buffer);
                buffer = new byte[1024];
            }
            out.flush();
        }catch (Exception e) {
            logger.error("访问远程文件出错咯!错误信息:" + e);
        }finally {
            try {
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                logger.error("出错咯!错误信息:" + e);
            }
        }
    }


最开始通过上面的代码能够访问共享文件并且下载文件,换了一个ip就不行了。报jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password,弄了很久,换了一种方式就可以了。


    public static void cmdFile() {
        String fileName = "";
        try {
            fileName = "you write file";
            File localFile = new File(fileName);

            String path = "//ip/server_file/myFile.jpg";
            if (!localFile.exists()) {
                localFile.createNewFile();
            }

            Runtime.getRuntime().exec("net use \\ip your_name /user:your_password");
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(path));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localFile));

            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
            out.flush();

        } catch (IOException e) {
            logger.error("出错咯!错误信息:" + e);
        }
    }

期间还报过jcifs.smb.SmbException: The system cannot find the file specified,最多的是该文件夹不存在。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值