Writing Inside a text file using Scanner Class

39,662

Solution 1

Scanner can't be used for writing purposes, only reading. I like to use a BufferedWriter to write to text files.

BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();

Solution 2

Scanner is for reading purposes. You can use Writer class to write data to a file.

For Example:

Writer wr = new FileWriter("file name.txt");
wr.write(String.valueOf(2))  // write int
wr.write("Name"); // write string

wr.flush();
wr.close();

Hope this helps

Share:
39,662
Vinay Verma
Author by

Vinay Verma

Updated on July 29, 2022

Comments

  • Vinay Verma
    Vinay Verma almost 2 years

    I have Come across so many programmes of how to read a text file using Scanner in Java. Following is some dummy code of Reading a text file in Java using Scanner:

    public static void main(String[] args) {
    
        File file = new File("10_Random");
    
        try {
    
            Scanner sc = new Scanner(file);
    
            while (sc.hasNextLine()) {
                int i = sc.nextInt();
                System.out.println(i);
            }
            sc.close();
        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
     }
    

    But, please anyone help me in "Writing" some text (i.e. String or Integer type text) inside a .txt file using Scanner in java. I don't know how to write that code.

  • Vinay Verma
    Vinay Verma about 8 years
    Ok, I didn't know that Scanner is for reading only. I will use this BufferedWriter class. Thanks a lot. :)
  • Vinay Verma
    Vinay Verma about 8 years
    Ok, I didn't know that Scanner is for reading only. I will use this Writer class. Thanks a lot. :)