我的一些 java 代码有问题。 我正在从一个方法返回一个文本,该文本位于 .txt 文件中。然后,我将此文本存储到变量“text”中,并将其写入另一个 .txt 文件。但问题是:这个新的 .txt 文件在底部出现了一个新的空行。那是因为在我的方法 read 中,变量“text”正在接收“\n”。我怎么解决这个问题? PS:我这样做是出于教育目的。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
public class Arquivo {
public static void main(String[] args) {
String text = read("in.txt");
write(text, "out.txt");
System.out.println("Text created!");
}
public static String read(String arquivo) {
String text = "";
try (BufferedReader br = new BufferedReader(new FileReader(arquivo))) {
String line = br.readLine();
while (line != null) {
text += line + "\n";
line = br.readLine();
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
return text;
}
public static void write(String text, String arquivo) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(arquivo))) {
bw.write(text);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
我创建的两个文件“in.txt”和“out.txt”。
这是 一个文本文件。
这是 一个文本文件。 (空行)
最佳答案
请尝试这个:
String line = br.readLine();
while (line != null) {
text += line;
line = br.readLine();
if (line!=null){
text += "\n";
}
}
你可以尝试这个变体:
String line;
while((line = br.readLine()) != null) {
text += line;
if (line!=null){
text += "\n";
}
}
关于java - 删除最后一个空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56192968/