材料:电脑 win10、一台安卓机
电脑 不需要密码可以自己访问文件夹
1.开启SMB1
win10基本都关闭了SMB1,但是win7是可以使用的,可以设置打开SMB1。也可以使用 SMB2/SMB3 。
![](https://img.haomeiwen.com/i1354448/f159254498757047.png)
2.无密码也可以访问文件夹
文件夹右键 --- 共享 --- 密码保护 -- “网络和共享中心”
打开后 所有网络 --- 密码保护的共享 -- 无密码保护的共享
3.取消文件夹只读属性
文件夹右键 --- 安全 --- 编辑 --- 添加 --- 左下角“高级” --- 立即查找 -- 找到Administrator(一般是只有一个人的那个)
当然这些是不推荐的,以为完全没有密码保护了,总归不安全。这次只记录无密码的情况,马上会更新有密码的。
Android代码
1.MyApp里加入
System.setProperty("jcifs.smb.client.dfs.disabled", "true");
System.setProperty("jcifs.smb.client.soTimeout", "1000000");
System.setProperty("jcifs.smb.client.responseTimeout", "30000");
2.加入jcifs
// 读取及写入网络共享文件
implementation group: 'jcifs', name: 'jcifs', version: '1.3.17'
3.连接写入文件(异步调用)
public static void upload(String ip, String folderName, String writeJson, String writeFileName) throws Exception {
File localFile = writeStringToFile(writeJson, writeFileName);
String remotePhotoUrl = "smb://" + ip + "/" + folderName;
SmbFile remoteFile = new SmbFile(remotePhotoUrl + "/" + localFile.getName());
remoteFile.connect(); //尝试连接
InputStream in = new BufferedInputStream(new FileInputStream(localFile));
OutputStream out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
try {
byte[] buffer = new byte[4096];
int len = 0; //读取长度
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
} finally {
try {
out.flush();//刷新缓冲的输出流
} catch (Exception e) {
e.printStackTrace();
DebugUtil.error("upload1" + e.getMessage());
}
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
DebugUtil.error("upload2" + e.getMessage());
}
}
}
public static File writeStringToFile(String json, String writeFileName) {
File file = new File(App.getInstance().getFilesDir(), writeFileName);
try {
PrintStream ps = new PrintStream(new FileOutputStream(file));
ps.println(json);// 往文件里写入字符串
// ps.append("http://www.jb51.net");// 在已有的基础上添加字符串
} catch (FileNotFoundException e) {
Log.e("writeStringToFile", "" + e.getMessage());
}
return file;
}
结果与注意事项
![](https://img.haomeiwen.com/i1354448/9718454ca66c4fec.png)
文件里是写入的json字符串。
注意事项:
- 连接到同一局域网!手机和电脑连接到同一局域网。
- 遵循smb协议,需要引入jcifs。
网友评论