Search code examples
javatry-catchwriter

String writer not writing to the file


The aim of my code is to eventually ask the user for a file name and if it is already a file in the current directory then print an error message, if it is not however then it is supposed to create the file and write lines to the newly created file until the user enters end. One final thing the program is supposed to keep doing this until the user enters exit. So in simpler terms the user enters a file name (its not a file already) they are prompted to input a line then another line, the user enters end and then the user is prompted to input a file name again and they type exit and the program stops. My code however which i will post is creating the file but not actually writing to it, help ?? I'm in java eclipse by the way

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
    }

Solution

  • You have forgotten to close the writer. And if you want to ensure, that you can see the changes while the program is still running, you have to flush after printing.

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