如何(或)是否可以使用 PrintWriter class 实现输入“*”以保存文件并在接受扫描仪输入后退出的逻辑?

How to (or) is it possible to implement logic to entering a " * " to save file and exit after taking scanner input, using PrintWriter class?

我正在尝试做这样的工作:

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

您正在比较字符串 * wrongly.You 应该使用 equals() 方法。 请替换

while((text=input.nextLine()) != "*")

while(!(text=input.nextLine()).equals("*"))