我正在尝试从文本文件input.txt中获取字符串文本,然后逐行将相同文本输出到输出文件output.txt
我已经尝试过了:
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
FileReader FR = new FileReader("C:\\FileLocation\\inputhashes.txt");
BufferedReader BR = new BufferedReader(FR);
PrintWriter PW = new PrintWriter("C:\\FileLocation\\outputtest.txt");
for (int i = 0; i < 8 ; i++) {
PW.println(BR.readLine());
}
}
但是这样做 不起作用,我不确定为什么,outputtest.txt文件完全为空。
当我尝试
System.out.println(BR.readLine());
控制台显示我期望的正确结果。
答案 0 :(得分:0)
以下代码将内容从一个文件复制到另一个文件,如@Robert Harvey所述,您可能无法正确关闭文件。
BufferedReader reader = Files.newBufferedReader(Paths.get("C:\\Users\\ngueno\\Desktop\\File 1.txt"));
BufferedWriter writer = Files.newBufferedWriter(Paths.get("C:\\Users\\ngueno\\Desktop\\File 2.txt"), StandardOpenOption.WRITE);
String line;
while( (line = reader.readLine()) != null ) {
writer.write(line);
}
reader.close();
writer.flush();
writer.close();
答案 1 :(得分:-1)
File inputFile = new File("inputFilePath");
File outputFile = new File("outputFilePath");
String output;
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader buffRead = new BufferedReader(new FileReader(inputFile))) {
String line;
while ( (line = buffRead.readLine()) != null) {
stringBuilder.append(line + "\n");
}
output = stringBuilder.toString();
} catch (Exception e) {
// handle exception
}
try (BufferedWriter buffWrite = new BufferedWriter(new FileWriter(outputFile))) {
buffWrite.write(output);
} catch (Exception e) {
// handle exception
}