Roki20121
Roki20121

Reputation: 115

Can't write text into file

I want to write int into text file. I wrote this code

public static void WriteInt(int i,String fileName){
    File directory = new File("C:\\this\\");
    if (!directory.exists()) {
        directory.mkdirs();
    }
    File file = new File("C\\"+fileName);
    FileOutputStream fOut = null;

    try {
        //Create the stream pointing at the file location
        fOut = new FileOutputStream(new File(directory, fileName));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    OutputStreamWriter osw = new OutputStreamWriter(fOut);
    try {

        osw.write(i);


        osw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

But in output file I have no int , just one symbol. Any ideas to do it?

Upvotes: 0

Views: 129

Answers (4)

JSlain
JSlain

Reputation: 576

I guess your problem is that you expected to literally find the number in human-readable format in your file, but the method of the OutputStreamWriter you're using (which receives a int) expect to receive a char representation. Have a look at the Ascii table for a reference of what int represents which char.

If you really wanted you write the number with characters, consider using a PrintWriter instead of a OutputStreamWriter. You could also change your int into a String (Integer.toString(i)) and still use your OutputStreamWriter

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53869

OutputStreamWriter is a stream to print characters.

Try using a PrintWriter like this:

try(FileWriter fw = new FileWriter(file); 
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw)) {
    pw.print(i);
}

Upvotes: 0

Sagar D
Sagar D

Reputation: 2618

 osw.write(i);

This line writes the character to the file whose unicode value is i

You should use PrintWriter to write your integer value.

Upvotes: 0

alamar
alamar

Reputation: 19343

You should be using PrintWriter.print(int)

Writer.write() outputs one character, that's what it's for. Don't get confused by int parameter type. Wrap your osw in PrintWriter, don't forget to close that.

Upvotes: 5

Related Questions