2015-05-03 19 views
3

我必須讀取可以是本地或遠程文件。
文件路徑或URI將來自用戶輸入。
目前我只讀取本地文件,這樣從URI的PATH讀取文件

public String readFile(String fileName) 
{ 

    File file=new File(fileName); 
    BufferedReader bufferedReader = null; 
    try { 
     bufferedReader = new BufferedReader(new FileReader(file)); 
     StringBuilder stringBuilder = new StringBuilder(); 
     String line; 

     while ((line=bufferedReader.readLine())!=null) { 
      stringBuilder.append(line); 
      stringBuilder.append(System.lineSeparator()); 
     } 
     return stringBuilder.toString(); 
    } catch (FileNotFoundException e) { 
     System.err.println("File : \""+file.getAbsolutePath()+"\" Not found"); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    finally { 
     try { 
      bufferedReader.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return null; 
} 

參數String fileName是用戶輸入可以是本地文件的路徑或URI
我怎麼能修改此方法既Local path工作和URI

+0

你可能看看這個鏈接 - http://stackoverflow.com/questions/1316360/reading-a-remote-file-using-java –

回答

4

Suposing你有URIString fileName您可以輕鬆地閱讀網址:

URI uri = new URI(filename); 
File f = new File(uri); 

檢查this link進一步信息

+0

對不起,如果我錯了,但我沒有看到任何'String類中的'toURI()'方法 – Saif

+0

對不起,我忘了字符串到uri轉換xDDDD –

+0

謝謝。我從你的答案中找到了一個很好的提示,但是確實如此。請編輯你的答案,我認爲還有一些事情要說清楚,比如'URI'對象上的url.toURI()'(我猜是錯字),我不需要考慮'URL' – Saif

0

File類也是基於URI所以說來容易,新構造文件(uri)..和一切都保持不變。 但是,URI是依賴於系統的,正如規範所述:「具有等於」file「的方案的絕對層次URI,非空路徑組件以及未定義的權限,查詢和片段組件」。

我認爲如果你需要讀取遠程的東西,最好的方法是使用套接字。