这个问题已经在这里有了答案:
我正在尝试获得以下工作:
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
class PrintWrit1
{
public static void main(String[] args)
{
Scanner input = new Scanner(in);
out.print("Enter the filename :\t");
String filename = input.nextLine();
try( PrintWriter pw = new PrintWriter(filename))
{
out.println("Enter the file content, enter * after finishing");
String text;
while((text=input.nextLine()) != "*")
{ pw.println(text); }
out.println(filename+" is saved and closed");
}
catch(IOException ioe)
{ ioe.printStackTrace();}
}
}
创建文件,写入输出,但保存命中文件时不会代替*,而是按ctrl-C,但随后的语句将不会执行,并且会突然终止。
我正在寻找关于此的任何建议,如果我在输入最后一行之后输入*,它应该能够执行out.println(filename+" is saved and closed")
电流输出:
D:\JavaEx\FILE-IO>java PrintWrit1
Enter the filename : sample
Enter the file content, enter * after finishing
line1
line2
*
预期产量:
D:\JavaEx\FILE-IO>java PrintWrit1
Enter the filename : sample
Enter the file content, enter * after finishing
line1
line2
*
sample is saved and closed