Java通过Samba服务操作Linux共享文件
首先在Linux上创建一个共享文件夹
mkdir /home/user/share
用root用户启动samba服务
service smb start
修改smb.conf文件
sudo gedit /etc/samba/smb.conf 或者 vi /etc/samba/smb.conf
[share]
path = /home/user/share
...
writable = yes
创建共享用户并设置密码
sudo useradd smbusr
sudo smbpasswd -a smbusr
使用命令 sudo smbpasswd -x 删除用户
重启samba服务
service smb restart
测试
在windows中输入\\192.168.0.94,并输入用户名密码smbusr/***,看能不能访问到共享文件夹。如果可以的话拷贝一份本地txt文件到此目录,并在linux中查看此文件是否存在,如果用vi能够打开文件文件并正常查看其内容,congruatulations!
用jcifs测试文件操作
去下
载适当版本的jcifs,将jcifs-1.3.14.jar加入到项目工程中。写个测试类共享文件操作:
public static void main(String[] args) {
FileInputStream fis = null;
SmbFileOutputStream sfos = null;
try {
fis = new FileInputStream(new File("c:/source.txt"));
sfos = new SmbFileOutputStream(new SmbFile("smb://smbusr:smbusr@192.168.1.94/smbusr/dest.txt"));
byte [] buffer = new byte[1024];
int c = 0;
while ((c = fis.read(buffer)) != -1) {
sfos.write(buffer);
}
} catch (SmbException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fis.close();
sfos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
相关文档:
2008 年 6 月 24 日