Java的new File获取另一台机器的文件
在Java中,使用new File()只能获取本机上的文件,如果需要获取另一台机器上的文件,需要使用网络文件共享协议,如SMB或NFS。以下是使用SMB协议获取另一台机器上的文件的示例代码:
import jcifs.smb.SmbFile;
public class SmbFileExample {
public static void main(String[] args) {
try {
String username = "username";
String password = "password";
String sharedFolder = "//192.168.1.100/sharedFolder/";
String filePath = "file.txt";
String sharedPath = sharedFolder + filePath;
SmbFile smbFile = new SmbFile(sharedPath, username, password);
if (smbFile.exists()) {
System.out.println("File exists!");
// do something with the file
} else {
System.out.println("File does not exist!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们使用了jcifs库来访问SMB共享文件。我们指定了共享文件的路径、用户名和密码,然后检查文件是否存在。如果文件存在,我们可以使用SmbFile对象执行其他操作,如复制、移动或删除文件
原文地址: https://www.cveoy.top/t/topic/hsc2 著作权归作者所有。请勿转载和采集!