Android 區域網路 - Jcifs-ng

Android 與 Windows之間可透過smb socket技術在區網中上傳或下載檔案。

之前提過使用Jcifs library來達成此功能,但是Jcifs只支援smb 1,而不支援smb 2/smb 3。

因此需要透過其他library來完成,如smbj或jcifs-ng。

由於smbj需要使用Android SDK 26 (Android O, Android 8),目前手邊沒有這些設備,所以本篇使用jcifs-ng來實做。

Step 1: 引用 Jcifs -ng

在Jcifs-ng官網中說明,引用Jcifs-ng只要在build.gradle中添加

build.gradle
1
2
3
4
5
<dependency>
<groupId>eu.agno3.jcifs</groupId>
<artifactId>jcifs-ng</artifactId>
<version>2.1.2</version>
</dependency>

亦可更改為

build.gradle
1
2
3
4
5
6
7
8
android {
...
}

dependencies {
...
compile 'eu.agno3.jcifs:jcifs-ng:2.1.2'
}

Step 2: 取得遠端檔案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
String userName = "user";
String password = "1234";
String remoteFile = "/files/test.csv";
String remoteURL = "smb://nickpublicpc";

CIFSContext baseCxt = new BaseContext(new PropertyConfiguration(System.getProperties()));
NtlmPasswordAuthenticator auth = new NtlmPasswordAuthenticator(userName, password);
CIFSContext ct = baseCxt.withCredentials(auth);
SmbFile smbFile = new SmbFile(remoteURL + remoteFile, ct);

SmbFileInputStream inputSmbFileStream = new SmbFileInputStream(smbFile);

File localFile = new File(filePath);
FileOutputStream outputFileStream = new FileOutputStream(localFile);

byte[] buffer = new byte[4096];
int length = 0;
while ((length = inputSmbFileStream.read(buffer)) > 0) {
outputFileStream.write(buffer, 0, length);
}

outputFileStream.close();
inputSmbFileStream.close();

以上便可透過smb server來取得區域網路中的文件,但Jcifs-ng只支援部份smb 3,需要看看往後版本會不會再更新了。

作者

Nick Lin

發表於

2019-04-09

更新於

2023-01-18

許可協議


評論