我正在尝试用java读取远程文件
File f = new File("//192.168.1.120/home/hustler/file.txt");
远程计算机需要用户名和密码才能访问该文件。
有没有办法可以通过java代码传递参数并读取文件?
package com.eiq;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemOptions;
import org.apache.commons.vfs.Selectors;
import org.apache.commons.vfs.UserAuthenticator;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.auth.StaticUserAuthenticator;
import org.apache.commons.vfs.impl.DefaultFileSystemConfigBuilder;
public class RemoteFileDemo {
public static void main(String[] args) throws IOException {
String domain = "hyd\\all";
String userName = "chiranjeevir";
String password = "Acvsl@jun2013";
String remoteFilePath = "\\\\10.0.15.74\\D$\\Suman\\host.txt";
File f = new File("E:/Suman.txt"); //Takes the default path, else, you can specify the required path
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileObject destn = VFS.getManager().resolveFile(f.getAbsolutePath());
//domain, username, password
UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password);
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile(remoteFilePath, opts);
System.out.println(fo.exists());
//fo.createFile();
destn.copyFrom(fo, Selectors.SELECT_SELF);
destn.close();
//InputStream is = new FileInputStream(f);
}
}
这是一个从远程计算机读取文件并将其作为文件存储在本地计算机中的程序E:/Suman.txt
.
写入文件路径时要小心,而不是:
我们必须将其替换为$
符号,例如:D:\Suman\Boorla\kpl.txt
是错的,D$\\Suman\\Boorla\\kpl.txt
是对的。
在上面的程序中,您必须更改远程计算机的域名、用户名、密码和文件路径。
要使用上面的程序,我们需要添加以下内容jar
类路径中的文件。
commons-vfs.jar
commons-logging.jar
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)