这是我的代码,我无法使其正常工作,它只从第一个文本文件中获得了总共3行的最后一行,并且仅将其大写,我无法弄清楚为什么
import java.util.Scanner;
import java.io.*;
public class AllCapitals {
public static void main(String[] args) {
String readLine;
String inFilePath = "/home/file.txt";
String outFilePath = "/home/newFile.txt";
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
readLine.toUpperCase();
String upperC = readLine.toUpperCase();
System.out.println(upperC);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFilePath), "utf-8"))) {
writer.write(upperC);
}
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
}
}
编辑:忘了说功能。
我需要从普通文本文件中读取3行
Hello.
How are you ?
Good, thank you !
输出应该在所有CAPS中,但我只得到最后一行“谢谢你”
答案 0 :(得分:2)
那是因为你在从第一次读取行的同时重新创建输出文件。 在开始阅读之前创建一次输出文件,例如:
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath));
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath), "utf-8"))
) {
while ((readLine = bufferedReader.readLine()) != null) {
String upperC = readLine.toUpperCase();
System.out.println(upperC);
writer.write(upperC);
writer.write(System.lineSeparator());
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
其他一些改进:
readLine.toUpperCase();
行