h-rai
h-rai

Reputation: 3974

writing to a text file but the contents of the file is not readable

I want to write the numbers to a file. The programs runs without any errors but when I open the file that I wrote to, the contents of the file is something like "!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ".

I cross-checked by reading the contents of the file using FileInputStream and printing the contents. The IDE prints the desired output but the integers in the file are not stored in readable form. Can anyone tell me why the integers are not populating in the file as intended?

import java.io.*;


public class Main {

    public static void main(String[] args) throws IOException{

        try{
        FileOutputStream fos = new FileOutputStream("Exercise_19.txt");

        for(int i = 0;i<=200; i++){
            fos.write((int)i);
        }
        fos.close();
        }
        catch(IOException ex){
        ex.printStackTrace();
        }

    }

Upvotes: 0

Views: 2330

Answers (3)

Lucifer
Lucifer

Reputation: 29670

FileOutputStream Class's Write() method will write the data in Byte format. so you can not read it in normal Notepad format. However you can read it using FileInputStream Class.

Syntax for Writing is as follows, look at this link

write(int b) 
          Writes the specified byte to this file output stream.

A Complete Writing and Reading Example you can find here.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533880

fos.write(int) writes a byte using the lowest 8-bits of the integer.

if you want to write text to a file, a simpler option is to use PrintWriter (note PrintWriter can use FileOutputStream so it can be done, but you really have to know what you are doing.)

public static void main(String... args) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter("Exercise_19.txt");
    for (int i = 0; i <= 200; i++)
        pw.println(i);
    pw.close();
}

Upvotes: 2

chooban
chooban

Reputation: 9256

Quite why you're getting that data in the file, I'm not sure, but the FileOutputStream is for writing raw bytes of data rather than human readable text. Trying using a FileWriter instead.

Upvotes: 3

Related Questions