Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Inside a text file using Scanner Class [duplicate]

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.

like image 743
Vinay Verma Avatar asked Dec 11 '22 17:12

Vinay Verma


1 Answers

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();
like image 112
jamesomahony Avatar answered Feb 16 '23 12:02

jamesomahony