Search code examples
javaprintwriter

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


I'm trying to get something like this work:

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();}
    }
}

File is created, output is written, but instead of * upon hitting ctrl-C, the file is saved but the statements following won't execute and it's terminating abruptly.

I'm looking for any suggestions for that if I enter * after entering the last line, it should be able to execute out.println(filename+" is saved and closed")

Current output:

D:\JavaEx\FILE-IO>java PrintWrit1
Enter the filename :    sample
Enter the file content, enter * after finishing
line1
line2
*

Expected output:

D:\JavaEx\FILE-IO>java PrintWrit1
Enter the filename :    sample
Enter the file content, enter * after finishing
line1
line2
*
sample is saved and closed

Solution

  • You are comparing the string * wrongly.You should use equals() method. Please replace

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

    to

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