我正在尝试将原件复制到新文件中。在新文件中,我想要与原始文件完全相同但没有空行。
注意:我查看了其他帖子,但没有成功。
目前:
1
2
3
我希望如何: - 没有空行
1
2
3
到目前为止,这是我的代码:
inputFileName = "x.txt";
outputFileName = "y.txt";
inputFile = new BufferedReader(new FileReader(inputFileName));
outputFile = new PrintWriter(new FileWriter(outputFileName));
String lineOfText = inputFile.readLine();
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
inputFile.close();
outputFile.close();
}
感谢所有可能提供帮助的人。我认为print("null")
会打印出“没有任何内容”。但它确实打印出null,我不知道如何打印出来'没有'。
答案 0 :(得分:1)
如果该行为空,则需要跳过println
:
while(lineOfText != null)
{
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
答案 1 :(得分:0)
你正走在正确的轨道上,但是这个
while(lineOfText != null)
{
if (lineOfText.isEmpty())
{
outputFile.print("null");
}
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
}
不应该在空行上写null
。我想你想要像
while(lineOfText != null)
{
if (!lineOfText.isEmpty())
{
outputFile.println(lineOfText);
}
lineOfText = inputFile.readLine();
}
,我建议您使用try-with-resources
Statement代替手动管理close
。在测试之前trim
(在评论中建议)可能是个好主意,您可以简化循环,并且应该限制变量可见性。总之喜欢,
String inputFileName = "x.txt";
String outputFileName = "y.txt";
try (BufferedReader inputFile = new BufferedReader(new FileReader(inputFileName));
PrintWriter outputFile = new PrintWriter(new FileWriter(outputFileName))) {
String lineOfText;
while ((lineOfText = inputFile.readLine()) != null) {
lineOfText = lineOfText.trim();
if (!lineOfText.isEmpty()) {
outputFile.println(lineOfText);
}
}
}
答案 2 :(得分:-1)
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data1.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}