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

it2022-05-05  128

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

//从共享目录下载文件 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,最多的是该文件夹不存在。


最新回复(0)