gpt4 book ai didi

java - Filereader.read() 方法不起作用

转载 作者:行者123 更新时间:2023-11-29 04:48:00 25 4
gpt4 key购买 nike

我编写了以下代码来创建一个文件,向其中添加文本,然后读取该文件。我的问题是在执行时,文件的内容没有显示在屏幕上,尽管内容被添加到文本文件中。

以下是我的代码

import java.io.*;
class prc4{
public static void main(String args[]){
try{
File f = new File("C:\\Program Files\\Java\\jdk1.8.0_25\\bin\\file1.txt");
if (f.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
FileWriter f1 = new FileWriter("file1.txt");
f1.write("Hello World. This is a sample text file!");
FileReader f2 = new FileReader("file1.txt");
int x = f2.read();
while(x != -1){
System.out.println((char)x);
x = f2.read();
}
f1.close();
f2.close();
}catch(Exception e){ }
}
}

输出: enter image description here

enter image description here

在文本文件中:

enter image description here

最佳答案

您需要关闭,或者至少 flush ,你从文件中读取之前的作者。写入文件是缓冲的,因此当您从文件中读取内容时,内容实际上并不在文件中。我建议使用 try-with-resources 构造关闭编写器:

try (FileWriter f1 = new FileWriter("file1.txt"))
{
f1.write("Hello World. This is a sample text file!");
}

try (FileReader f2 = new FileReader("file1.txt");)
{
int x = f2.read();
while(x != -1){
System.out.println((char)x);
x = f2.read();
}
}

另外请注意,您正在为每个字符调用 println(),这意味着每个字符将打印在单独的行上。这可能是您想要的,或者您可能想要调用 print()

关于java - Filereader.read() 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com