Search code examples
javafilewriter

Is there a way for FileWriter.write() to continue writing strings after spaces in runtime?


When I'm trying to run this piece,

import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;

class  CSWrite1
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(in);
        out.print("Enter the filename\t>"); 
        String file = input.next();
        out.println("Enter the text");
        String text = input.next();  // IN:"Hello, How are you" --> "Hello,

        try(FileWriter fw = new FileWriter(file))
        { fw.write(text); }
    }
}

while giving input to text as "Hello, How are you" The file is written only with "Hello,. The remaining text after the first space is not being written into the file.


Solution

  • The following works for me:

    import static java.lang.System.*;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;
    
    public class CSWrite1 {
        public static void main(String[] args) {
            try (Scanner input = new Scanner(in)) {
                out.print("Enter file name> ");
                String file = input.nextLine();
                try (FileWriter fw = new FileWriter(file)) {
                    out.print("Enter text: ");
                    String text = input.nextLine(); // IN:"Hello, How are you" --> "Hello,
                    fw.write(text);
                }
                catch (IOException xIo) {
                    xIo.printStackTrace();
                }
            }
        }
    }