我的代码的目的是最终向用户询问文件名,如果它已经是当前目录中的文件,则打印错误消息,如果不是,那么它应该创建文件并写入直到用户输入结束为止,直到新创建的文件。程序最后应该继续这样做,直到用户进入退出状态。所以简单来说,用户输入一个文件名(它不是文件),提示他们输入一行,然后输入另一行,用户输入end,然后提示用户再次输入文件名,然后键入exit和程序停止。然而,我将发布的代码是创建文件,但实际上并没有写入它,帮助?我一直在java eclipse中
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
}
答案 0 :(得分:1)
你忘了关闭作家了。 如果您想确保在程序仍在运行时可以看到更改,则必须在打印后进行刷新。
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();
答案 1 :(得分:0)
我在这里可以看到两个问题。一个你没有关闭编写器,第二个,你有与导入类(PrintWriter)相同的类名。因此,当您声明Printwriter的实例时,它将创建您的类的实例而不是java.io.Printwriter。