Java操作網絡共享資源
一、背景介紹
1、有些需求中需要定時將信息寫入到對方開發的共享文件夾中,這時就需要進行遠程操作。
2、這個使用需要對方共享文件夾開放對應的讀寫權限。
3、這次用的是CIFS,通用Internet文件系統,在windows主機之間進行網絡文件共享是通過使用微軟公司自己的CIFS服務實現的。
二、實現邏輯
1、共享的文件夾常見的有兩種:訪問時需要用戶名+密碼和訪問時不需要文件名和密碼,這都有文件夾設置的權限決定。
2、smb://用戶名:密碼@IP/文件路徑 VS smb://IP/文件路徑
3、讀取操作是將共享文件以流的方式返回了,若要提取則可以寫入到文件流中。
4、寫入操作也是將操作編程對流的操作,通過NtlmPasswordAuthentication("",username(沒有即爲null),password(沒有即爲null)對象將遠程目錄當成本地來操作。
5、將流對象自己拷貝到遠程文件中。
三、具體操作。
1、對遠程文件進行讀取操作。
SmbFile smbFile = new SmbFile("smb://administrator:[email protected]/share/a.txt");
int length = smbFile.getContentLength();//得到文件的大小
byte buffer[] = new byte[length];
SmbFileInputStream in = new SmbFileInputStream(smbFile); //建立smb文件輸入流
while ((in.read(buffer)) != -1) {
System.out.write(buffer);
System.out.println(buffer.length);
}
in.close();
2、對遠程文件寫入操作。
OutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
"username", "password");
try {
SmbFile remoteFile = new SmbFile(remoteName, auth);
SmbFile remoteDir = new SmbFile(remoteFile.getParent(), auth);
// create remote folder if not exist
if (!remoteDir.exists())
remoteDir.mkdirs();
// create remote file
if (!remoteFile.exists())
remoteFile.createNewFile();
remoteFile.setReadWrite();
byte[] buf;
int len;
try {
fileInputStream = new FileInputStream(localName);
fileOutputStream = remoteFile.getOutputStream();
buf = new byte[16 * 1024 * 1024];
while ((len = fileInputStream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fileInputStream.close();
fileOutputStream.close();
}
3、需要的maven配置。
<dependency>
<groupId>jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.17</version>
</dependency>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.