前言
由於在和第三方公司對接的過程中涉及到附件發送及格式等相關的問題,經討論后采用共享文件夾的方式,在我們這邊產生新的數據時將數據打包發送到共享文件夾下,他們再需要的時候自動從文件夾下讀取數據,避免了數據傳輸出現的其他各種奇怪的問題。
實現
引入jar包
<!-- https://mvnrepository.com/artifact/org.samba.jcifs/jcifs -->
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.3</version>
</dependency>
實現代碼
// 共享文件夾所在服務器ip
private static String USER_DOMAIN = "192.168.xxx.xxx";
//訪問用戶
private static String USER_ACCOUNT = "userxx";
//訪問密碼
private static String USER_PWS = "xxx";
//共享文件夾地址
private static final String shareDirectory = "smb://192.168.xxx.xxx/dir";
//字節長度
private static final int byteLen = 1024;
/**
*
* @Title smbPut
* @Description 向共享目錄上傳文件
* @Param shareDirectory 共享目錄
* @Param localFilePath 本地目錄中的文件路徑
* @date 2019-01-10 20:16
*/
public void smbPut(String shareDirectory, File localFile) {
InputStream in = null;
OutputStream out = null;
try {
String fileName = localFile.getName();
// 域服務器驗證
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(USER_DOMAIN, USER_ACCOUNT,
USER_PWS);
SmbFile remoteFile = new SmbFile(shareDirectory + "/" + fileName, auth);
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
byte[] buffer = new byte[byteLen];
while (in.read(buffer) != -1) {
out.write(buffer);
buffer = new byte[byteLen];
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}