Android中如何访问网络共享文件夹并执行文件操作?
Android访问网络共享文件夹(SMB)的实现方案
一、JCIFS-NG库(你提到的方案)
JCIFS-NG确实是Android上访问SMB共享的主流方案之一,只是官方文档不够直观,这里整理核心实现步骤:
- 添加依赖:在Module级别的
build.gradle中引入最新稳定版依赖:implementation 'eu.agno3.jcifs:jcifs-ng:2.1.30' - 核心操作示例:
- 建立SMB连接:
// 配置共享地址、用户名、密码 SmbFileContext context = new SmbFileContextBuilder() .withCredentials(new NtlmPasswordAuthentication(null, "your_username", "your_password")) .build(); SmbFile sharedFolder = new SmbFile("smb://192.168.1.100/your_shared_folder/", context); - 遍历共享目录:
if (sharedFolder.exists() && sharedFolder.isDirectory()) { SmbFile[] files = sharedFolder.listFiles(); for (SmbFile file : files) { // 处理文件/文件夹,比如获取名称:file.getName() } } - 读取文件:
SmbFile targetFile = new SmbFile("smb://192.168.1.100/your_shared_folder/test.txt", context); InputStream in = targetFile.getInputStream(); // 后续使用read()等方法,和本地文件流用法一致 in.close(); - 写入文件:
SmbFile newFile = new SmbFile("smb://192.168.1.100/your_shared_folder/new_file.txt", context); OutputStream out = newFile.getOutputStream(); out.write("测试内容".getBytes()); out.close();
- 建立SMB连接:
- 注意事项:
- 必须申请网络权限:
android.permission.INTERNET;Android 10+若使用非HTTPS的共享地址,需在AndroidManifest.xml的<application>标签内添加android:usesCleartextTraffic="true" - 所有SMB操作不能在主线程执行,需用线程池、Coroutine或AsyncTask处理,避免阻塞UI
- 必须申请网络权限:
二、Android 11+原生SMB API(推荐)
从Android 11(API 30)开始,系统提供了android.net.smb原生API,无需第三方库,稳定性更好:
- 权限与配置:
- 添加权限:
android.permission.ACCESS_SMB、android.permission.INTERNET - 在
AndroidManifest.xml的<application>标签内声明库依赖:<uses-library android:name="android.net.smb" android:required="false" />
- 添加权限:
- 核心操作示例:
- 获取SmbManager实例:
SmbManager smbManager = context.getSystemService(SmbManager.class); - 配置共享与凭证:
SmbCredential credential = new SmbCredential.Builder("your_username", "your_password".toCharArray()) .setDomain("WORKGROUP") // Windows默认工作组为WORKGROUP .build(); SmbShare share = new SmbShare.Builder("192.168.1.100", "your_shared_folder") .setCredential(credential) .build(); - 打开文件流:
smbManager.openFile(share, "test.txt", SmbManager.OPEN_MODE_READ_ONLY, null, new SmbCallback<SmbFileInputStream>() { @Override public void onSuccess(SmbFileInputStream result) { // 读取文件,和本地InputStream用法一致 } @Override public void onFailure(SmbException e) { // 处理连接或文件操作异常 } });
- 获取SmbManager实例:
- 优势:系统原生支持,兼容性更强,官方文档规范,无需维护第三方库依赖
三、底层方案:libsmbclient
若需要极致性能或底层操作,可以使用Samba官方的libsmbclient库,但需要通过NDK编译集成,实现门槛较高,仅适合对性能有特殊要求的场景,普通应用不推荐使用
内容的提问来源于stack exchange,提问作者Anirudh Kachroo
相关产品推荐
相关产品推荐

