Search code examples
javaiofilewriter

I can't manipulate name of the file that filewriter class creates


I am working on a simple program that takes input from user and then saves it with specific file name.

To be more precise:

public static Scanner in = new Scanner(System.in);
public static boolean quit = false;
public static String name;
public static FileWriter fw;

public static void main(String[] args) throws IOException {

    System.out.print("File name: ");
    name = in.nextLine();

    fw = new FileWriter(name + ".txt", false);
    System.out.println("Continue typing/type save to quit");
    while(!quit) {
        String word = in.nextLine();
        if(word.equals("save")) {

            fw.close();
            quit = true;
        }

        else {              
            fw.write(word + "\n");
        }

    }
  1. Program asks for file name.
  2. User is typing words until he types "save" which saves the file

As you can see program ask user for file name at the beginning, before he starts to type. This is my problem. I want my program to ask the user for a file name at the end, after he typed all words. Unfortunately I cant do this because filewriter class creates the file when new object is created and name cannot be changed later.

I would like to know is there any solution to my problem or what kind of information should I look for.


Solution

  • You have two options:

    1. Store all the user input in memory (in a List<String> for instance) and then write out the words after seeing the save keyword and getting the output filename from the user.
    2. Open the output file as you are doing, but with a temporary name, and write the words as you read them. Upon seeing the save keyword, close the file, get the user's chosen filename, and then rename the temporary file to the user's choice.

    Unless you need to process millions of words I'd go with option 1 for its simplicity.