将多行合并为一行
Combining multiple lines into one single line
我有一个如下所示的文本文件:
thiasisatest("test1",
"test2",
"test3",
"test4",
"test5");
我试图实现的输出是这样的:
thiasisatest("test1", "test2", "test3", "test4", "test5");
我的代码如下所示:
import java.io.*;
public class IoTest {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Applications/textfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.trim().replace("\n", ""));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
我正在读取该行并替换 while 循环中的所有行,但输出没有改变,当我尝试打印字符串时这些行仍然存在。
我做错了什么?
感谢您的帮助
System.out.println
终止该行,这就是为什么你得到多行。
其实你不需要更换线;因为你技术上是逐行回忆。
您需要做的就是创建一个 StringBuilder,您可以将缓冲的 reader.
中的每一行附加到其中
您的代码应如下所示
String sCurrentLine;
StringBuilder builder = new StringBuilder();
while ((sCurrentLine = br.readLine()) != null){
builder.append(sCurrentLine);
}
您现在可以将 "builder" 的内容输出到另一个文件。
我有一个如下所示的文本文件:
thiasisatest("test1",
"test2",
"test3",
"test4",
"test5");
我试图实现的输出是这样的:
thiasisatest("test1", "test2", "test3", "test4", "test5");
我的代码如下所示:
import java.io.*;
public class IoTest {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("/Applications/textfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.trim().replace("\n", ""));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
我正在读取该行并替换 while 循环中的所有行,但输出没有改变,当我尝试打印字符串时这些行仍然存在。
我做错了什么?
感谢您的帮助
System.out.println
终止该行,这就是为什么你得到多行。
其实你不需要更换线;因为你技术上是逐行回忆。
您需要做的就是创建一个 StringBuilder,您可以将缓冲的 reader.
中的每一行附加到其中您的代码应如下所示
String sCurrentLine;
StringBuilder builder = new StringBuilder();
while ((sCurrentLine = br.readLine()) != null){
builder.append(sCurrentLine);
}
您现在可以将 "builder" 的内容输出到另一个文件。