4

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.

2
  • 3
    Scanner is for reading, not for writing. Commented Apr 29, 2016 at 7:01
  • 2
    consider OutputStream for your purpose Commented Apr 29, 2016 at 7:03

2 Answers 2

9

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I didn't know that Scanner is for reading only. I will use this BufferedWriter class. Thanks a lot. :)
4

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

1 Comment

Ok, I didn't know that Scanner is for reading only. I will use this Writer class. Thanks a lot. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.