[英]How to read a file from remote system using java?
我有一個文件復制到一台計算機,我需要從其他計算機訪問該文件。 我不確定,使用哪種協議或哪種技術? 請給我任何提示......
我正在使用Ubuntu Linux系統。 我用過代碼:
File f = new File("//192.168.1.157/home/renjith/picture.jpg");// 192.168.1.157 is the ip of the computer, where I have the picture file
Image image = ImageIO.read(f);
但它給出了一個例外:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1275)
我也共享了renjith文件夾。
有許多方法可以訪問遠程計算機上的文件,但它們幾乎都依賴於已經設置的遠程計算機以先以某種方式提供文件。 如果您要通過java訪問文件,最簡單的方法可能是在遠程計算機上設置HTTP服務器(這可以在各種平台上使用Apache HTTP服務器輕松完成),然后使用Apache Commons HTTPClient客戶端Java應用程序。 有關如何安裝或配置它們的進一步討論通常超出了Stack Overflow的范圍,並且至少需要更具體的問題
HTTP是一種選擇。 但是,如果這些是同一LAN上的Windows計算機,則通過文件共享公開遠程計算機上的目錄並通過常規文件路徑訪問該文件會更容易。 同樣,如果這些是類Unix機器,如果您使用NFS,則可以使用常規文件路徑。 FTP是另一種選擇。
如果遠程計算機位於同一網絡中,並且位於運行Java代碼的計算機的共享文件夾中,請嘗試使用此代碼訪問它
File file = new File("\\\\Comp-1\\FileIO\\Stop.txt");
這里Comp-1是包含網絡文件的機器的DNS名稱!
你可以試試:
URL url = new URL("file://192.168.1.157/home/renjith/picture.jpg");
Image image = ImageIO.read(url);
您可以先嘗試安裝該路徑,然后加載它。 做一個:
subst x: \\192.168.1.157
然后:
File f = new File("x:\\home\\renjith\\picture.jpg");
Image image = ImageIO.read(f)
它應該工作。
共享目錄並訪問文件thruogh java code試試這個:
File f = new File("//10.22.33.122/images")
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
// Specify the extentions of files to be included.
return name.endsWith(".bmp") || name.endsWith(".gif");
}
});
// get names of the files
String[] fileNamesArray = null;
for (int indx = 0; indx < files.length(); indx++) {
fileNamesArray[indx] = files[indx].getName();
}
return fileNamesArray;
您可以使用java中的jcifs-1.3.15.jar jar從遠程讀取並寫入遠程,但首先您需要從遠程系統共享位置然后才可能。
try{
String strLine="";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("WORKGROUP", "username", "passwd"); // Authentication info here, domain can be null
// try (InputStream is = new SmbFile("smb://DESKTOP-0xxxx/usr/local/cache/abc.txt", auth).getInputStream()) {
try (InputStream is = new SmbFile("smb://xx.xx.xx.xxx/dina_share/abc.txt", auth).getInputStream()) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException e) {
e.printStackTrace();
}
String smbURL="smb://xx.xx.xx.xxx/dina_share/abcOther.txt";
SmbFileOutputStream fos = new SmbFileOutputStream(new SmbFile(smbURL,auth));
byte bytes[]="Wellcome to you".getBytes();
fos.write(bytes);
}catch(Exception e){
e.printStackTrace();
}
將您的IP映射到網絡驅動器,然后讓我們說驅動器號是X,
然后代碼更改為File f = new File("x:\\\\home\\\\renjith\\\\picture.jpg");
實際上你的文件已經加載到對象f
,嘗試將路徑f.getAbsolutePath()
的值f.getAbsolutePath()
到控制台並查看..實際錯誤與ImageIO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.