Hello!!!

mmm am learning OOP in Java ... and now I'm facing a prob in reading/writing .txt file
here's my code:

import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.FileNotFoundException;

public class Tester {
    public static void main(String[] args)
    {
        Scanner scan = null;
        Formatter formatter = null;
        File fileI;
        File fileO;

        fileI = new File("/home/amir/workspace/ForExam1/src/Class1/input.txt");
        fileO = new File("/home/amir/workspace/ForExam1/src/Class1/output.txt");

        try {
            scan = new Scanner(fileI);
            formatter = new Formatter(fileO);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int first = scan.nextInt();

        formatter.format("%d", first);
    }
}

and here the input.txt file:

123

The code is generating the "output.txt" file put it's empty, I SOP the 'first' variable which has the value of '123' and it worked ... but the code is not writing the value of 'first' in the output.txt ...

Anyidea how to fix this code??.

Thank you, Regards

You need a file writer of some sort... Scanner class is a read-in for input but not for outputing. There are many ways to write data to file. Here is an example of how to write to file. I googled it...

Hey Taywin, actually I read this example, and fixed my code. The problem was that I didn't close the formatter

formatter.close();

but anyway the other way is also a nice one thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.