Sunjaree
Sunjaree

Reputation: 138

Facing problem in writing and reading on file using Formatter in java

Here, I can write on the file. But when I'm trying to read my file it's giving me "MyFile.txt" but my output should be " I'm 20" What is wrong in my code?

import java.util.*;
class main{
    public static void main(String[] args){

        Formatter fr;

        try{
            fr = new Formatter("MyFile.txt");

            fr.format("I'm %d",20);

            fr.close();

        }catch (Exception e){
            System.out.println("Error");
        }

        try {
            Scanner sc = new Scanner("MyFile.txt");
            while (sc.hasNext()){
                System.out.println(sc.next());
            }
             sc.close();
        }catch (Exception e){
            System.out.println("Error");
        }

    }
}

Upvotes: 1

Views: 165

Answers (1)

Bill the Lizard
Bill the Lizard

Reputation: 405805

You're passing a string literal to the Scanner constructor.

Scanner sc = new Scanner("MyFile.txt");

That's the constructor that scans the string itself.

You want to pass it a File object instead:

Scanner sc = new Scanner(new File("MyFile.txt"));

Note: Writing to a file with a Formatter the way you do works because the Formatter constructor that takes a String assumes that the string is a file name. The Scanner constructor assumes that the string itself is the input, not a file name.

Upvotes: 7

Related Questions