2016-04-24 52 views
0

我有一個構造函數如下:如何將文件內容轉換爲字符串?

MyClassName(File f) throws Exception; 

和TXT文件看起來是這樣的:

. . . . . 
. . . . . 
. x . . . 
. x x . . 
. . . . . 
. . . . . 

當打開該文件,我怎麼把它轉換爲字符串?

像這樣:

". . . . .\n 
. . . . .\n 
. x . . .\n 
. x x . .\n 
. . . . .\n 
. . . . .\n" 
+0

目前還不清楚你的意思 - 這有點聽起來像你想創建一個字符串文字,但是你不能有多行字符串文字(不是沒有明確地連接這些行,反正)。 –

+2

'新的字符串(Files.readAllBytes(f.toPath()))' –

+0

@ElliottFrisch值得一提這裏的文件編碼 - 平臺默認可能不正確。雖然它的內容不應該有太大的影響。 –

回答

0

此方法讀取一個文件:

public String readFile(File file) { 
    StringBuffer stringBuffer = new StringBuffer(); 
    if (file.exists()) 
     try { 
      //read data from file 
      FileInputStream fileInputStream = new FileInputStream(file); 
      int c; 
      while ((c = fileInputStream.read()) != -1){ 
       stringBuffer.append((char) c); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    return stringBuffer.toString(); 
} 

和呼叫從構造

public MyClassName(File f) throws Exception{ 
    String text = readFile(f); 
} 
+0

愚蠢的問題 - 這是怎麼比'新字符串(Files.readAllBytes(f.toPath()))'?這肯定是**更長時間...... –

相關問題