1.業務場景:甲方系統會不定期將一批xls文件存放到windows服務器的共享文件夾下,這些文件將作為本系統的數據來源,需要自動維護到本系統的數據庫中。
2.准備工作:
①確保windows服務器的smb服務啟動,如果未啟動,在啟用或關閉windows功能中開啟
②確保存放的目錄已經作為共享文件夾
3.代碼
<dependency> <groupId>jcifs</groupId> <artifactId>jcifs</artifactId> <version>1.3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
public static void main(String[] args) throws IOException { remoteFile(".docx"); uploadFile("smb://192.168.1.96/myDownload/","C:\\Users\\USERNAME\\Desktop\\orders.txt"); } public static SmbFile getShareedRoot() throws IOException { String remoteShareRoot = "smb://192.168.1.96/myDownload/"; NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://192.168.1.96/", "USERNAME", "PASSWORD"); SmbFile remoteFile = new SmbFile(remoteShareRoot,auth); remoteFile.connect(); //嘗試連接 return remoteFile; } public static SmbFile getSpecified(String remote) throws IOException { NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("smb://192.168.1.96/", "USERNAME", "PASSWORD"); SmbFile remoteFile = new SmbFile(remote,auth); remoteFile.connect(); //嘗試連接 return remoteFile; } //查看共享文件列表 public static SmbFile[] listFiles (SmbFile shareRoot) throws SmbException { return shareRoot.listFiles(); } public static void downloadFile (SmbFile file) throws IOException { String fileName = file.getName(); String localFile = fileName.substring(fileName.lastIndexOf("\\") + 1); try(InputStream in = new BufferedInputStream(new SmbFileInputStream(file)); FileOutputStream out = new FileOutputStream(new File(localFile));){ byte[] buffer = new byte[4096]; int len = 0; //讀取長度 while ((len = in.read(buffer, 0, buffer.length)) != - 1) { out.write(buffer, 0, len); } out.flush(); //刷新緩沖的輸出流 } } public static void uploadFile (String shareFileRoot, String localFilePath) { try { File localFile = new File(localFilePath); String fileName = localFile.getName(); SmbFile file = getSpecified(shareFileRoot); //當成file用 if (!file.exists()){ file.mkdirs(); } //下面一行本來打算想新建File在指定目錄下並且指定文件名,后面發現第一個參數與File同方法參數意義不同 SmbFile remoteFile = new SmbFile( file.getURL() + "/" + fileName); IOUtils.copy(new FileInputStream(localFile), new SmbFileOutputStream(remoteFile)); } catch (Exception e) { e.printStackTrace(); } } public static void remoteFile(String want) throws IOException { SmbFile shareRoot = getShareedRoot(); SmbFile smbFile = Arrays.stream(listFiles(shareRoot)).filter(x -> x.getName().endsWith(want)).findAny().get(); downloadFile(smbFile); }