在java中读取需要用户名和密码的远程文件

我试图在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 

使用jCIFS的另一种方法是您可以轻松指定身份validation参数:

 NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain", "user", "password"); // Authentication info here, domain can be null try (InputStream is = new SmbFile("smb://192.168.1.120/home/hustler/file.txt", auth).getInputStream()) { // Read from 'is' ... } catch (IOException e) { // Handle IOException } 

你也可以试试Commons VSF 。 检查UserAuthenticator

这是代码,我写的,它完美地工作。

 File f=new File("abc.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()); UserAuthenticator auth = new StaticUserAuthenticator("", "myusername", "secret_password"); FileSystemOptions opts = new FileSystemOptions(); DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); FileObject fo = VFS.getManager().resolveFile("\\\\192.168.0.1\\direcory\\to\\GetData\\sourceFile.txt",opts); destn.copyFrom(fo,Selectors.SELECT_SELF); destn.close(); 

现在,您可以使用该文件执行所需的操作。 就像是…

 InputStream is = new FileInputStream(f);