2017-06-05 92 views
-1

我有這樣的代碼從類路徑 A =其文本文件加載的文件,我用什麼IM想讀給串 是:如何從File對象在java中讀取文本文件

File file = new File(classLoader.getResource("sample.json").getFile()); 

我不想使用:

file.getAbsolutePath(); 

我怎樣才能讀取這個文本文件到字符串?

UPDATE 我找到了解決方案,您怎麼看?

ClassLoader classLoader = getClass().getClassLoader(); 
is = classLoader.getResourceAsStream("sample.json"); 
String txt = IOUtils.toString(is); 
+2

什麼相關性'file.getAbsolutePath();'處理您的問題? –

+0

請參閱https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html –

+0

'Files.readAllLines();' –

回答

1

如果您使用的是Java 8,你可以用這個從文件中讀取行:

List<String> lines = Files.readallLines(file.toPath()); 

請參考下面的文檔:

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-

https://docs.oracle.com/javase/8/docs/api/java/io/File.html#toPath--

編輯:

爲了從你得到了作爲一個InputStream資源閱讀,你可以使用的BufferedReaderInputStreamReader組合:

String getText() throws IOException{ 
    StringBuilder txt = new StringBuilder(); 
    InputStream res = getClass().getClassLoader().getResourceAsStream("sample.json"); 
    try (BufferedReader br = new BufferedReader(new InputStreamReader(res))) { 
     String sCurrentLine; 
     while ((sCurrentLine = br.readLine()) != null) { 
      txt.append(sCurrentLine + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return txt.toString(); 
} 

希望這有助於!

0

您可以使用下面的代碼來讀取文件對象。

public static void main(String[] args) { 

     try (BufferedReader br = new BufferedReader(file)) { 
      String sCurrentLine; 
      while ((sCurrentLine = br.readLine()) != null) { 
       System.out.println(sCurrentLine); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    }