Home > Software design >  Whenever I use scanner to write in a file,it just prints one word in the file
Whenever I use scanner to write in a file,it just prints one word in the file

Time:11-23

import java.io.*;
import java.util.Scanner;

public class create {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String fileStr="javaDemo.txt";
        File f1=new File("D://downloads//" fileStr);
        try{
            System.out.println("Give content:");
            String data=sc.next();
            FileWriter writer=new FileWriter(f1.getAbsolutePath());
            BufferedWriter bufferedWriter=new BufferedWriter(writer);
            bufferedWriter.write(data);
            bufferedWriter.close();
        }catch (Exception e){
            System.out.println("error:" e);
            e.printStackTrace();
        }

    }
}

Output

file

Expected output: Hello world text in file

Actual output: only Hello text in file

CodePudding user response:

You're using sc.next() which reads until the 1st whitespace, if you want to read an entire line you should use the sc.readLine() method that would read all the lines until the Enter the user inserts.

Moreover, when using all of the above resources you should remember to close them in your final block, or even better use try-with-resources as shown below:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    File file = new File("javaDemo.txt");

    System.out.println("Give content:");

    try (FileWriter writer = new FileWriter(file.getAbsolutePath());
         BufferedWriter bufferedWriter = new BufferedWriter(writer)
    ) {
        String data = sc.nextLine();
        bufferedWriter.write(data);
    } catch (IOException e) {
        System.out.println("error:"   e);
        e.printStackTrace();
    }
}

If you want to write multiple lines into the file wrap the body of the try with a loop that will read from the user and flash it to the file

CodePudding user response:

Scanners start off using 'any whitespace' as delimiter. next() retrieves the next token, and a token is defined as 'that which is in between delimiters'. In other words, it gets you 1 word.

You may instead want Scanner to treat 'a new line' as delimiter. Then, the 'stuff between the delimiters' is entire lines, which appears to be what you want. In which case, simply tell it:

scanner.useDelimiter("\\R");

Is all it takes. \\R is regexpese for 'any newline'. Due to OS differences there are a few different takes on what a newline is, fortunately, \\R is a convenient catch-all.

NB: Using scanner for keyboard input? You should probably always set the delimiter like this too; universally pretty much user input is separated out by pressing enter, so scanner out-of-the-box isn't suitable for handling keyboard input. Even though 99.99% of stack overflow examples do so, which is unfortunate.

  • Related