[英]Read remote file in java which needs username and password
我正在嘗試用 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的另一種選擇,您可以輕松指定身份驗證參數:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.