java获取局域网其他机器上的共享文件

导入依赖 jcifs

  1. <dependency>
  2. <groupId>jcifs</groupId>
  3. <artifactId>jcifs</artifactId>
  4. <version>1.3.17</version>
  5. </dependency>

windows启用smb服务

在控制面板->程序和功能->启用或关闭Windows功能->启用smb服务,重启电脑生效。

给windows电脑设置用户名和密码

注意:需不需要用户名密码这是必须要知道的,不然无法读取,可以自己测试一下,(ctrl+r 输入://192.168.2.188 回车,如果需要账户名密码的话,会弹出一个对话框的)

测试代码

  1. public static void main(String[] args) throws IOException {
  2. //在192.168.2.188的电脑上,用户名为:Administrator,密码为:123456
  3. SmbFile file = new SmbFile("smb://Administrator:123456@192.168.2.188/test123/test.txt");
  4. ///在192.168.2.188的电脑上,没有用户名和密码
  5. /// SmbFile file = new SmbFile("smb://192.168.2.188/test123");
  6. SmbFileInputStream in = new SmbFileInputStream(file);
  7. byte bt[] = new byte[1024];
  8. int c;
  9. while ((c = in.read(bt)) != -1) {
  10. System.out.println("开始从192.168.2.188电脑上面读取数据");
  11. }
  12. System.out.println(new String(bt, "gb2312"));
  13. }

获取文件夹最新的文件名字

  1. public static void main(String[] args) throws IOException {
  2. String url="smb://Administrator:123456@192.168.2.188/test123/";
  3. SmbFile file;
  4. try {
  5. file = new SmbFile(url);
  6. if(file.exists()){
  7. SmbFile[] files = file.listFiles();
  8. for (int i = 0; i < files.length; i++) {
  9. for (int j = i + 1; j < files.length; j++) {
  10. if (files[i].getLastModified() < files[j].getLastModified()) {
  11. SmbFile temp = files[j];
  12. files[j] = files[i];
  13. files[i] = temp;
  14. }
  15. }
  16. }
  17. System.out.println(files[0].getName());
  18. }
  19. } catch (MalformedURLException e) {
  20. e.printStackTrace();
  21. } catch (SmbException e) {
  22. e.printStackTrace();
  23. }
  24. }