public class UploadDownloadUtil { /** * 从共享目录拷贝文件到本地 * @param remoteUrl 共享目录上的文件路径 * @param localDir 本地目录 */ public void smbGet(String remoteUrl, String localDir) { InputStream in = null; OutputStream out = null; try { SmbFile remoteFile = new SmbFile(remoteUrl); //这一句很重要 remoteFile.connect(); if (remoteFile == null) { System.out.println("共享文件不存在"); return; } String fileName = remoteFile.getName(); File localFile = new File(localDir + File.separator + 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 { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 从本地上传文件到共享目录 * @Version1.0 Sep 25, 2009 3:49:00 PM * @param remoteUrl 共享文件目录 * @param localFilePath 本地文件绝对路径 */ public void smbPut(String remoteUrl, String localFilePath) { InputStream in = null; OutputStream out = null; try { File localFile = new File(localFilePath); String fileName = localFile.getName(); SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName); in = new BufferedInputStream(new FileInputStream(localFile)); out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) { out.write(buffer); buffer = new byte[1024]; } } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { UploadDownloadUtil test = new UploadDownloadUtil(); // smb:域名;用户名:[email protected]/文件夹/文件名.xxx // test.smbGet("smb://szpcg;jiang.t:[email protected]/Jake/test.txt", // "c://") ; // test.smbPut("smb://szpcg;jiang.t:[email protected]/Jake", // "c://test.txt"); //用户名密码不能有强字符,也就是不能有特殊字符,否则会被作为分断处理 test.smbGet("smb://CHINA;xieruilin:[email protected]/project/report/网上问题智能分析助手使用文档.doc", "c://Temp/"); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10980.html