ASHISH
ASHISH

Reputation: 67

Writing Into a file using Java

 public static void writeIntoFile() {
        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("Employee.txt");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(list1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream == null) {
                System.out.println("file is not created");
            }
            if (objectOutputStream == null) {
                System.out.println("cant able to write");
            }
        }
    }

I want to using this function to writing in a file. it writes successfully but it display data in bytecode. how can I save it into string format?

Upvotes: 1

Views: 1104

Answers (3)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

Use a FileWriter wrapped inside a BufferedWriter to write character data to a File.

ObjectOutputStream is used for serialization and results in a binary encoded file. Its only useful if you only want to load the file through your program and do not wish to read its contents elsewhere like in an external editor.

You also need to iterate through your List and save the requisite properties of your underlying Object in a format you wish to parse your File later on in. For example, as CSV (comma separated values) every Employee object and its properties would be persisted as one single line in the output file.

BufferedWriter br = new BufferedWriter(new FileWriter("Employee.csv"));
for (Employee employee : list) {
    br.write(employee.getFName() + ", " + employee.getLName());
    br.newLine();
}
br.close();

Upvotes: 3

Alkesh_IT
Alkesh_IT

Reputation: 376

you can change bytecode into string using one simple way. pass the bytecode into string constructor like this:

new String(bytecode object);

and then write string object into file.

Upvotes: 0

yaphet
yaphet

Reputation: 310

in the function writeIntoFile is write a Serialization Object into file

you should use the object's toString() to write a String into file

Upvotes: 0

Related Questions