2016-04-28 158 views
0

我有以下文本文件。我一次讀取每行,並將整行推入字符串。目前,我的代碼只是逐行讀取每行,不用擔心任何空格,所以Java閱讀多行文本文件,在最後一個字符後在每行末尾添加分隔符

random text變成randomtext。有沒有辦法在行中的最後一個字符之後插入一個空格?我嘗試了下面的代碼,但它沒有完成這項工作。

d = d.replaceAll("\n", " ");

TextFile.txt的

Text random text random numbers etc. This is a random 
text file. 
+0

如何你是在讀線? –

回答

4

在閱讀中的臺詞,沒有在你的字符串中的任何 '\ n' 字符。所以,你需要做的就是通過空間加入這些線。只需使用String.join()

在Java 8中,所有你需要的是:

File f = new File("your file path"); 
List<String> lines = Files.readAllLines(file.toPath()); 
String result = String.join(" ", lines); 

UPDATE

正如希雷在下面的評論中指出,如果該文件是巨大的規模,這是更好地使用緩衝讀取器讀取每行並用空格連接它們。

下面是如何使用BufferredReader

File file = new File("file_path"); 
StringBuilder sb = new StringBuilder(); 

try (BufferedReader reader = new BufferedReader(new FileReader(file))) { 
    String line; 

    while ((line = reader.readLine()) != null) { 
     sb.append(line).append(" "); 
    } 
} catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
} 
String result = sb.toString(); 
+0

如果文件的行數太多,最好使用BufferedReader一次讀取一行,並在StringBuilder中構建字符串,在除最後一行之外的每行之後添加一個空格「'。 –

+0

@ShireResident是的,我同意。我將在答案中包括這一點。謝謝。 –

相關問題