1

Nothing appears in file using following code. If I change the UserString to "Hello" for example it works and prints to the file. I've checked the value of UserString within try and it prints the correct value but i cant figure out why the printWriter won't use the value.

    public void writeToAFile()
    {
        FileOutputStream outputStream = null;
        PrintWriter printWriter = null;

        System.out.println("Please enter the name of the file:");
        Scanner UserFileNameInput = new Scanner(System.in);
        FileName = UserFileNameInput.nextLine();
        if(FileName != "")
        {
            do {
                System.out.println("Please enter a string:");
                Scanner UserStringInput = new Scanner(System.in);
                UserString = UserStringInput.nextLine();

                try
                {
                    outputStream = new FileOutputStream(FileName+".txt");
                    printWriter = new PrintWriter(outputStream);
                    printWriter.println(UserString);
                }
                catch(IOException e)
                {
                    System.out.println("Error in file write: " + e);
                }

                }while(UserString.length() != 0);
            printWriter.close();
            System.exit(0);
        }
        else
        {
            System.out.println("Please enter a valid input");
            writeToAFile();
        }
    }

    public static void main(String[] args)
    {
        Files writeToAFileObject = new Files();
        writeToAFileObject.writeToAFile();
    }
boyslime
  • 11
  • 2
  • 2
    What is `FileName`? --- What is `UserString`? --- `if(FileName != "")` is wrong, see [How do I compare strings in Java?](https://stackoverflow.com/q/513832/5221149) --- Don't create multiple `Scanner` objects on `System.in`. --- Use try-with-resources when using `Writer` and `OutputStream` objects. – Andreas Nov 12 '19 at 18:37
  • @Andreas I think the OP isn't following Java's naming conventions – Shankha057 Nov 12 '19 at 18:39
  • 1
    Your file is empty because your code keeps running until you press enter without entering any text, i.e. until `UserString.length() == 0`, but before exiting, the program **writes that empty string to the file**, *overriding* any previous file content, since you create the `FileOutputStream` **inside the loop**, even though you close it outside the loop *(Huh?!?)*. – Andreas Nov 12 '19 at 18:39
  • @Shankha057 True, but what does that have to do with my comment? I'm asking what `FileName` is, because it hasn't been **declared** anywhere. Sure I can guess that it's a `String`, but I shouldn't have to guess. – Andreas Nov 12 '19 at 18:40

0 Answers0