2009-08-22 129 views
14

我正在尋找一種簡單的方法來獲取位於遠程服務器上的文件。爲此,我創建了我的Windows XP本地FTP服務器,現在我想給我的測試小程序中的下列地址:使用Java讀取遠程文件

try 
{ 
    uri = new URI("ftp://localhost/myTest/test.mid"); 
    File midiFile = new File(uri); 
} 
catch (Exception ex) 
{ 
} 

,當然我收到以下錯誤:

URI scheme is not "file"

我一直在嘗試一些其他的方式來獲取文件,他們似乎沒有工作。我應該怎麼做? (我也熱衷於執行一個HTTP請求)

回答

19

你不能用ftp開箱。

如果你的文件是在HTTP上,你可以做類似的東西:通過http

URL url = new URL("http://q.com/test.mid"); 
InputStream is = url.openStream(); 
// Read from is 

如果你想用做FTP庫,你應該檢查出Apache Commons Net

8

讀二進制文件並將其保存到本地文件(從here拍攝):

URL u = new URL("http://www.java2s.com/binary.dat"); 
URLConnection uc = u.openConnection(); 
String contentType = uc.getContentType(); 
int contentLength = uc.getContentLength(); 
if (contentType.startsWith("text/") || contentLength == -1) { 
    throw new IOException("This is not a binary file."); 
} 
InputStream raw = uc.getInputStream(); 
InputStream in = new BufferedInputStream(raw); 
byte[] data = new byte[contentLength]; 
int bytesRead = 0; 
int offset = 0; 
while (offset < contentLength) { 
    bytesRead = in.read(data, offset, data.length - offset); 
    if (bytesRead == -1) 
    break; 
    offset += bytesRead; 
} 
in.close(); 

if (offset != contentLength) { 
    throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes"); 
} 

String filename = u.getFile().substring(filename.lastIndexOf('/') + 1); 
FileOutputStream out = new FileOutputStream(filename); 
out.write(data); 
out.flush(); 
out.close(); 
4

你幾乎沒有。您需要使用URL而不是URI。 Java帶有用於FTP的默認URL處理程序。例如,可以讀取遠程文件到字節數組這樣,

try { 
     URL url = new URL("ftp://localhost/myTest/test.mid"); 
     InputStream is = url.openStream(); 
     ByteArrayOutputStream os = new ByteArrayOutputStream();   
     byte[] buf = new byte[4096]; 
     int n;   
     while ((n = is.read(buf)) >= 0) 
      os.write(buf, 0, n); 
     os.close(); 
     is.close();   
     byte[] data = os.toByteArray(); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

然而,FTP可能無法在一個applet使用的最佳協議。除了安全限制之外,由於FTP需要多個端口,您將不得不處理連接問題。如果其他人所建議的都可能,請使用HTTP。

-5

由於您在Windows上,您可以設置網絡共享並以此方式訪問它。

0

這對我有用,同時試圖將文件從遠程機器上傳到我的機器上。

注 - 這些都傳遞到下面的代碼中提到的函數的參數:

String domain = "xyz.company.com"; 
String userName = "GDD"; 
String password = "fjsdfks"; 

(在這裏你必須給遠程系統的機器的IP地址,然後將文本文件的路徑( testFileUpload.txt)在遠程機器上,在這裏C$意味着遠程系統的C盤,另外的IP地址與\\開始,但爲了躲避兩個反斜槓我們啓動\\\\

String remoteFilePathTransfer = "\\\\13.3.2.33\\c$\\FileUploadVerify\\testFileUpload.txt"; 

(H ERE這是本地機器在該文件已被轉移的路徑,它將創建這個新的文本文件 - testFileUploadTransferred.txt,用遙控器上的文件中的內容 - testFileUpload.txt這是遠程系統上)

String fileTransferDestinationTransfer = "D:/FileUploadVerification/TransferredFromRemote/testFileUploadTransferred.txt"; 

import java.io.File; 
import java.io.IOException; 

import org.apache.commons.vfs.FileObject; 
import org.apache.commons.vfs.FileSystemException; 
import org.apache.commons.vfs.FileSystemManager; 
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 FileTransferUtility { 

    public void transferFileFromRemote(String domain, String userName, String password, String remoteFileLocation, 
      String fileDestinationLocation) { 

     File f = new File(fileDestinationLocation); 
     FileObject destn; 
     try { 
      FileSystemManager fm = VFS.getManager(); 

      destn = VFS.getManager().resolveFile(f.getAbsolutePath()); 

      if(!f.exists()) 
      { 
       System.out.println("File : "+fileDestinationLocation +" does not exist. transferring file from : "+ remoteFileLocation+" to: "+fileDestinationLocation); 
      } 
      else 
       System.out.println("File : "+fileDestinationLocation +" exists. Transferring(override) file from : "+ remoteFileLocation+" to: "+fileDestinationLocation); 

      UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password); 
      FileSystemOptions opts = new FileSystemOptions(); 
      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); 
      FileObject fo = VFS.getManager().resolveFile(remoteFileLocation, opts); 
      System.out.println(fo.exists()); 
      destn.copyFrom(fo, Selectors.SELECT_SELF); 
      destn.close(); 
      if(f.exists()) 
      { 
       System.out.println("File transfer from : "+ remoteFileLocation+" to: "+fileDestinationLocation+" is successful"); 
      } 
     } 

     catch (FileSystemException e) { 
      e.printStackTrace(); 
     } 

    } 

} 
0

我編寫了一個Java Remote File客戶機/服務器對象來訪問遠程文件系統,就好像它是本地一樣。它沒有任何身份驗證(這是當時的觀點),但它可以修改爲使用SSLSocket而不是標準套接字進行身份驗證。

它是原始訪問:沒有用戶名/密碼,沒有「home」/ chroot目錄。

一切都保持儘可能簡單:

服務器設置

JRFServer srv = JRFServer.get(new InetSocketAddress(2205)); 
srv.start(); 

客戶端安裝

JRFClient cli = new JRFClient(new InetSocketAddress("jrfserver-hostname", 2205)); 

您通過訪問遠程FileInputStreamOutputStream客戶。它擴展java.io.File使用File訪問它的元數據API中使用無縫(即length()lastModified(),...)。

它還使用可選的壓縮功能對文件塊傳輸和可編程MTU進行優化的全文檢索。 CLI爲最終用戶內置了類似於FTP的語法。