Java 字符串编写器未写入文件
我的代码的目的是最终要求用户提供一个文件名,如果它已经是当前目录中的一个文件,则打印一条错误消息,如果不是,则应该创建该文件并向新创建的文件写入行,直到用户进入end。最后一件事是程序应该一直这样做,直到用户进入退出。因此,更简单地说,用户输入一个文件名(它已经不是一个文件了),系统会提示用户输入一行,然后再输入另一行,用户输入end,然后提示用户再次输入一个文件名,然后输入exit,程序停止。但是,我将发布的代码正在创建文件,但实际上并没有写入文件,帮助??顺便说一下,我现在在java eclipse中Java 字符串编写器未写入文件,java,try-catch,writer,Java,Try Catch,Writer,我的代码的目的是最终要求用户提供一个文件名,如果它已经是当前目录中的一个文件,则打印一条错误消息,如果不是,则应该创建该文件并向新创建的文件写入行,直到用户进入end。最后一件事是程序应该一直这样做,直到用户进入退出。因此,更简单地说,用户输入一个文件名(它已经不是一个文件了),系统会提示用户输入一行,然后再输入另一行,用户输入end,然后提示用户再次输入一个文件名,然后输入exit,程序停止。但是,我将发布的代码正在创建文件,但实际上并没有写入文件,帮助??顺便说一下,我现在在java ecl
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class PrintWriter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
PrintWriter writer = null;
// Initializes the printwriter as writer
try
{
writer = new PrintWriter("printwriter3.txt", "UTF-8");
// will write in the UTF-8 language to a file named printwriter.txt
boolean exit = false;
while (exit == false)
{
String user = input.nextLine();
if (user.equals("end"))
{
exit = true;
}
else
{
writer.println(user);
}
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("File not found");
// if the file is not found then this error message is printed
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("The encoding type is not supported");
// if the encoding type in this case UTF-8 is not supported an error message is printed
}
你忘了关上书写器。 如果要确保在程序仍在运行时可以看到更改,则必须在打印后刷新
writer = new PrintWriter("printwriter3.txt", "UTF-8");
// will write in the UTF-8 language to a file named printwriter.txt
boolean exit = false;
while (exit == false)
{
String user = input.nextLine();
if (user.equals("end"))
{
exit = true;
}
else
{
writer.println(user);
writer.flush();
}
}
writer.close();
我可以看到两个问题。一个是未关闭writer,另一个是与导入的类(PrintWriter)具有相同的类名。因此,当您声明Printwriter的实例时,它将创建您的类的实例,而不是java.io.Printwriter。您在完成编写器时是否关闭了它?您没有关闭编写器。另外,Java7还实现了一个带有资源的Try/Catch块。以下是参考资料:。此方法负责关闭。