1准备工作:
(1)mac【系统偏好】->【用户与群组】->【用户与群组】->点左下角解锁 “+” 新建一个用户"share"(账户类型仅限共享,名称密码必填,自己随便命名)
(2)mac【系统偏好】->【共享】->勾选 【文件共享】(使用SMB来共享文件和文件夹),切换到【用户】点“+”选择刚刚新建的用户"share"
2 AndroidStudio:
(1)app目录下 build.gradle 下添加 implementation 'com.hierynomus:smbj:0.10.0'
(2)异步线程使用:
val client = SMBClient()
val connection = client.connect("192.168.0.xxx")
val ac = AuthenticationContext("share", "share000".toCharArray(), "192.168.0.xxx")
val session: Session = connection.authenticate(ac)
val share = session.connectShare("共享的文件夹") as DiskShare?
share?.list("子文件夹")?.forEach {
Log.e("Tag","smb -> ${it.fileName}")
}
//下载文件
val filePath="共享的文件夹/子文件夹/xxx.txt"
val smbFileRead = share.openFile(filePath, EnumSet.of(AccessMask.GENERIC_READ), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, null)
val input = smbFileRead.inputStream
val outFile = File(Environment.getExternalStorageDirectory().absolutePath, "temp.txt")
val out = FileOutputStream(outFile)
try {
// Transfer bytes from in to out
val buf = ByteArray(4096)
var len = input.read(buf)
while (len > 0) {
out.write(buf, 0, len)
len = input.read(buf)
}
input.close()
} catch (e: IOException) {
e.printStackTrace()
} finally {
out.close()
}
3注意的地方:
(1)不要用guest账户,不要用anonymous账户