目的:使用java代码读取到局域网下linux的某个文件信息
设置linux共享文件夹
一.安装Samba
yum -y install samba samba-client samba-common
二.修改Samba配置文件
1.配置内核参数
ulimit -n 16384
vi /etc/security/limits.conf
#在最后面加上一下内容:避免在启动Samba时出现警告信息
* - nofile 16384
2.修改配置文件
cd /etc/samba/
#修改smb.conf文件
#修改[global]配置内容,并新添加[SHAREDOCS]内容。SHAREDOCS为共享文件夹名(本例访问共享文件夹不需要用户名和密码)
#其他的不需要改动
[global]
workgroup = WORKGROUP
netbios name=SHAREDOCS
server string=Samba Server
security = user
map to guest = Bad User
[SHAREDOCS]
path=/ 注意:path的值为你要共享的文件夹名称,此处我选择了根目录
writable=yes
browseable=yes
public= yes
guest ok=yes
三.重启服务
systemctl restart smb
systemctl enable smb
systemctl status smb
四.让Samba通过防火墙
#1.设置开机自动关闭防火墙
systemctl disable firewalld
#2.配置/etc/sysconfig/iptables文件,添加以下内容
-A INPUT -m state --state NEW -m tcp -p tcp --dport 139 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 445 -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 137 -j ACCEPT
-A INPUT -m state --state NEW -m udp -p udp --dport 138 -j ACCEPT
#3.重启防火墙
systemctl restart firewalld
五.关闭SELINUX
vim /etc/selinux/config
把SELINUX的值改为disabled,之后需重启系统
reboot
六.访问
电脑输入 \\虚拟机ip即可
读取共享文件夹信息
一.maven添加依赖
<!--smb协议获取共享文件夹内容-->
<dependency>
<groupId>jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.17</version>
</dependency>
二.工具类代码
package org.springblade.common.utils;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import java.io.*;
public class ReadFileUtils {
public static void main(String[] args){
ReadFileUtils test = new ReadFileUtils() ;
// smb:域名;用户名:密码@目的IP/文件夹/文件名.xxx smb://192.168.8.178/aa/1.txt
//共享文件夹名
String shareFolder = "aa/";
//共享文件名
String fileName = "1.txt";
String remoteUrl = "smb://192.196.8.178/" + shareFolder + fileName;
test.smbGet(remoteUrl, "d:/") ;
}
/**
* Description: 从共享目录拷贝文件到本地
* @param remoteUrl 共享目录上的文件路径
* @param localDir 本地目录
*/
public void smbGet(String remoteUrl,String localDir) {
InputStream in = null;
OutputStream out = null;
try {
SmbFile remoteFile = new SmbFile(remoteUrl);
if(remoteFile==null){
System.out.println("共享文件不存在");
return;
}
String fileName = remoteFile.getName();
File localFile = new File(localDir+File.separator+fileName);
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
out = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[1024];
while(in.read(buffer)!=-1){
out.write(buffer);
buffer = new byte[1024];
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}