在閱讀中的臺詞,沒有在你的字符串中的任何 '\ 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();
如何你是在讀線? –