MiloradP
MiloradP

Reputation: 41

FileInputStream Error

I have this piece of code, just to try to write it to a file. But when I compile it, it doesn't display any errors, but text in my file is unreadable, some Unicode codes etc... I use eclipse IDE. What could be the reason for this?

public static void main(String[] args) {

    String s = "Hello world!";
    int i = 143141141;
    try
    {
        //create new file with an ObjectOutputStream
        FileOutputStream out = new FileOutputStream("test.txt");
        ObjectOutputStream oout = new ObjectOutputStream(out);

        //write something in a file
        oout.writeObject(s);
        oout.writeObject(i);
        //close the stream
        oout.close();

        //create an ObjectInputStream for the file we created before
        ObjectInputStream ois = new ObjectInputStream(
                                                new FileInputStream("test.txt"));
        //read and print what we wrote before
        System.out.println("" + (String) ois.readObject());
        System.out.println("" + ois.readObject());
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

Upvotes: 0

Views: 577

Answers (9)

sultan.of.swing
sultan.of.swing

Reputation: 1116

You're making the folly of writing the output string through an ObjectOutputStream which serializes the String and Integer objects in your code and saves the Object state along with the value of the object. This is the reason why you see encoded text when you open the file. The following excerpt sums up the values which are stored when an Object is serialized:

The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.(ObjectOutputStream)

The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it.

Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. (ObjectOutputStream javadoc)

Upvotes: 0

Ankur Trapasiya
Ankur Trapasiya

Reputation: 2200

The possible problem with your code is you are not flushing the output data. So that it might not get written to the output file.

Try the below code.

public static void main(String[] args) {

    String s = "Hello world!";
    int i = 143141141;
    try
    {
        //create new file with an ObjectOutputStream
        FileOutputStream out = new FileOutputStream("test.txt");
        ObjectOutputStream oout = new ObjectOutputStream(out);

        //write something in a file
        oout.writeObject(s);
        oout.flush();
        oout.writeObject(i);
        oout.flush();        
        //close the stream
        out.close();
        oout.close();

        //create an ObjectInputStream for the file we created before
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
        //read and print what we wrote before
        System.out.println("" + (String) ois.readObject());
        System.out.println("" + ois.readObject());
        ois.close();
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}

And also if you want to read your written objects into the file then you can't because they are written as serialized objects. For textual operation with files you can consider BufferedReader or PrintWriter. see the following code.

public class WriteToFileExample {
    public static void main(String[] args) {
        try {

            String content = "This is the content to write into file";

            File file = new File("c:\\desktop\\filename.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

After this you can open your text file and can see the written content in the human readable form and it is good practice to not to give "txt" formats when you are writing objects to the file. It's misleading.

Hope this helps.

Upvotes: -1

Sumit Desai
Sumit Desai

Reputation: 1770

I tried your code. It's working perfectly for me. See the attached image. enter image description here

Try cleaning your workspace. If it doesn't work, try creating a new Java project and copy the same code posted here and try. It should work.

Upvotes: 0

pinkpanther
pinkpanther

Reputation: 4808

You are not writing values of your String and Integer objects but their object representations in binary format. That is called object-serialization. That is some how encoded to represent all the information associate with the object not only its value That is only displayed when decoded in the same way as we encoded them. So, normal text editor cannot display the information as you expected.

If you want to save the string representation only, use the classes such as PrintWriter.

Upvotes: 0

Harish Kumar
Harish Kumar

Reputation: 528

Your code is working fine for me. If I understand it correctly when look at the contents of file by opening it in editor (say notepad or eclipse) you see characters stored as binary content in it. As you are using ObjectInputStream and ObjectOutputStream the behavior is correct.

Upvotes: 0

eternay
eternay

Reputation: 3814

With an ObjectOutputStream, you're using Serialization to write your objects to a file. Serialization is using an encoding system, and you use correctly an ObjectInputStream in your program to decode these objects. But you won't be able to read the information in the file created by the Serialization process.

Upvotes: 2

anshulkatta
anshulkatta

Reputation: 2064

Since you are using ObjectOutputStream and ObjectInputStream , it will write in Object code , which is not readable , and as well when u read from file , it will come up as an Object so again as an Object ,

Use BufferedReader or Writer to write String into file , which can be read

FileReader f=new FileReader(new File("test.txt"));
BufferedReader f1=new BufferedReader(f)

;

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

Java ObjectOuputStream writes objects in a binary non human readable format which can be read only with ObjectInputStream.

Upvotes: 0

Grzegorz Żur
Grzegorz Żur

Reputation: 49241

You should use PrintWriter to write text files, ObjectOutputStream writes binary data.

Upvotes: 0

Related Questions