Java file read objects

Java files read and write multiple objects

Before sorting out file read and write objects, review the contents of file read and write:

Character stream and byte stream

1. Character stream

In the process of transmission, the most basic unit of transmitted data is the stream of characters

Read file contents through BufferedReader:

public static void readFile() throws IOException < Path path = Paths.get("data.txt"); BufferedReader reader = Files.newBufferedReader(path); String lineContent = reader.readLine(); while (lineContent != null) < System.out.println(lineContent); lineContent = reader.readLine(); >reader.close(); >

BufferedReader: extended from the Reader class, it provides a general buffering method for text reading to improve efficiency, and provides a very practical readLine() method

Write to the file through BufferedWriter:

public static void writeFile(String[] data) throws IOException < Path path = Paths.get("data.txt"); BufferedWriter writer = Files.newBufferedWriter(path); for (int i=0;iwriter.close(); >

2. Byte stream

In the process of transmission, the most basic unit of transmitted data is the stream of bytes

Read file contents through BufferedInputStream:

public static void readFile() throws IOException < FileInputStream file = new FileInputStream("data.txt"); BufferedInputStream reader = new BufferedInputStream(file); byte[] buff = new byte[MAX_SIZE]; while ((len = reader.read(buff)) != -1) < System.out.println(new String(buff, 0, len)); >reader.close(); file.close(); >

new String(byte bytes[], int offset, int length, String charsetName); : Encodes a binary array by specifying a character set and converts it to string form.

Читайте также:  Downgrade my java version

Write to the file through BufferedOutputStream:

public void writeFile(String data) throws IOException

BufferedInputStream and BufferedOutputStream: a stream that improves efficiency by encapsulating other streams, so you need to instantiate another stream before use.

3. Difference between character stream and byte stream

In essence, whether reading or writing data, binary is accessed in bytes. Byte stream is to directly read or write the file content in binary form. If we want to know the read content, we need to specify an encoding method. When writing, we need to convert it to byte type. The character stream has its own encoding, so we don’t need to convert it manually when reading and writing, and the basic unit is the size of the character.

Object read and write

To read and write files to an object, you need to make the object implement an interface Serializable first

Serializable is a semantic level interface defined in the java.io package to implement the serialization of classes. The serializable interface does not have any methods or fields, but is only used to identify serializable semantics. The class that implements the serializable interface can be represented as a byte sequence, which includes the data of the object, information about the type of the object and the type of data stored in the object. It can be converted into a byte stream by ObjectOutputStream, and can also be parsed into an object by ObjectInputStream.

1. Read an object

public void readObject() throws IOException, ClassNotFoundException

2. Write an object

public void writeObject(YourClassName Data) throws IOException

3. Read multiple objects

public List readMulObject() throws IOException < Listlst = new ArrayList<>(); FileInputStream file = new FileInputStream(new File("data.txt")); ObjectInputStream reader = new ObjectInputStream(file); while (true) < try < YourClassName Cls = (YourClassName) reader.readObject(); lst.add(Cls); >catch (EOFException e) < System.out.println("Read complete"); break; >> file.close(); reader.close(); return lst; >

4. Write multiple objects

public void writeFile(List lst) throws IOException < FileOutputStream file = new FileOutputStream(new File("data.txt")); ObjectOutputStream writer = new ObjectOutputStream(file); for (YourClassName Cls : lst) < writer.writeObject(Cls); >writer.close(); >

There is a problem here. When writing objects, they will be written from the beginning of the file by default, which will overwrite the original contents of the file. If you want to add a write to the back of the file, you need FileOutputStream file = new FileOutputStream(new File(«data.txt»), 1) but there will be another problem: each time you open the file, the program will add an ACED 0005 field before writing information by default, but when reading, it will mistakenly think it is a part of the object, resulting in parsing errors. At present, I haven’t found a perfect solution to this problem. The current measure is to use the List to take out all the contents before writing the file, then add all the written information to the List, and then store the whole List in the file.

Posted on Sun, 05 Dec 2021 03:27:04 -0500 by RockRunner

Hot Tags

  • Java — 7906
  • Database — 3176
  • Python — 3103
  • Attribute — 2963
  • Programming — 2938
  • Javascript — 2788
  • Spring — 2575
  • xml — 2270
  • Android — 2243
  • Linux — 2204
  • JSON — 2150
  • less — 2137
  • network — 2115
  • github — 2063
  • MySQL — 1760
  • SQL — 1616
  • PHP — 1559
  • encoding — 1360
  • Mobile — 1172
  • Apache — 1137

Источник

How to read and write Java object to a file

Java object Serialization is an API provided by Java Library stack as a means to serialize Java objects. Serialization is a process to convert objects into a writable byte stream. Once converted into a byte-stream, these objects can be written to a file. The reverse process of this is called de-serialization.

A Java object is serializable if its class or any of its superclasses implement either the java.io.Serializable interface or its subinterface, java.io.Externalizable .

1. Java Object

 package com.mkyong; import java.io.Serializable; public class Person implements Serializable < private static final long serialVersionUID = 1L; private String name; private int age; private String gender; Person() < >; Person(String name, int age, String gender) < this.name = name; this.age = age; this.gender = gender; >@Override public String toString() < return "Name:" + name + "\nAge: " + age + "\nGender: " + gender; >> 

2. Writing and Reading objects in Java

The objects can be converted into byte-stream using java.io.ObjectOutputStream . In order to enable writing of objects into a file using ObjectOutputStream , it is mandatory that the concerned class implements Serializable interface as shown in the class definition below.

Reading objects in Java are similar to writing object using ObjectOutputStream ObjectInputStream . Below example shows the complete cycle of writing objects and reading objects in Java.

On reading objects, the ObjectInputStream directly tries to map all the attributes into the class into which we try to cast the read object. If it is unable to map the respective object exactly then it throws a ClassNotFound exception.

Let us now understand the writing and reading process using an example. We are using the Person class shown above as an object.

 package com.mkyong; package com.mkyong; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class WriterReader < public static void main(String[] args) < Person p1 = new Person("John", 30, "Male"); Person p2 = new Person("Rachel", 25, "Female"); try < FileOutputStream f = new FileOutputStream(new File("myObjects.txt")); ObjectOutputStream o = new ObjectOutputStream(f); // Write objects to file o.writeObject(p1); o.writeObject(p2); o.close(); f.close(); FileInputStream fi = new FileInputStream(new File("myObjects.txt")); ObjectInputStream oi = new ObjectInputStream(fi); // Read objects Person pr1 = (Person) oi.readObject(); Person pr2 = (Person) oi.readObject(); System.out.println(pr1.toString()); System.out.println(pr2.toString()); oi.close(); fi.close(); >catch (FileNotFoundException e) < System.out.println("File not found"); >catch (IOException e) < System.out.println("Error initializing stream"); >catch (ClassNotFoundException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > 

On executing the above code, we get below output:

 Name:John Age: 30 Gender: Male Name:Rachel Age: 25 Gender: Female 

References

Datsabk

A technically sound person, oriented towards learning things logically rather than technically. It is my logical approach that has helped me learn and take up any programming language and start with coding. With a responsibility of Java based Web development professionally, I highly believe in imparting knowledge online for any technical subject that I can handle.

Источник

How to read an Object from a File in Java

In an earlier article, we looked at how to write an object to a file using Java. In this short article, you’ll learn how to read a Java Object from a file or how to deserialize the serialized object saved in a file.

The deserialization process is quite similar to the serialization process. Basically, to read an object from a file, you need to follow the below steps:

  • Open the file that has the Java Object stored using FileInputStream .
  • Create an instance of ObjectInputStream and pass FileInputStream as an argument to its constructor.
  • Use ObjectInputStream.readObject() method to read the object from the file.
  • The above method will return a generic object of type Object . You need to cast this object to its original type to properly use it.

Here is how our User.java class looks like that we used to write an object to a file in the previous article:

public class User implements Serializable  public String name; public String email; private String[] roles; private boolean admin; public User()  > public User(String name, String email, String[] roles, boolean admin)  this.name = name; this.email = email; this.roles = roles; this.admin = admin; > // getters and setters, toString() . (omitted for brevity) > 

The following example shows how you can deserialize the object.dat file and convert it back to a User object in Java 7 or higher:

try (FileInputStream fis = new FileInputStream("object.dat"); ObjectInputStream ois = new ObjectInputStream(fis)) < // read object from file User user = (User) ois.readObject(); // print object System.out.println(user); >catch (IOException | ClassNotFoundException ex)
Username='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true> 

If you are using an older Java version (Java 6 or below), you have to manually close ObjectInputStream as shown below:

try  FileInputStream fis = new FileInputStream("object.dat"); ObjectInputStream ois = new ObjectInputStream(fis); // read object from file User user = (User) ois.readObject(); // print object System.out.println(user); // close reader ois.close(); > catch (IOException | ClassNotFoundException ex)  ex.printStackTrace(); > 

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Program: How to store and read objects from a file?

Sometimes we need to store the objects to the file system, and need to read them whenever required. Below example shows how to store the objects to the file, and how to retrieve them from the file. ObjectInputStream and ObjectOutputStream classes can help us to store and read objects from a file.

Java File IO Operations Sample Code Examples

  1. All file operations.
  2. Show list of all file names from a folder.
  3. How to get list of all files from a folder?
  4. Filter the files by file extensions and show the file names.
  5. How to read file content using byte array?
  6. How to read file content line by line in java?
  7. How to read property file in static context?
  8. How to read input from console in java?
  9. How to get file list from a folder filtered by extensions?
  10. How to get file URI reference?
  11. How to store and read objects from a file?
  12. How to create and store property file dynamically?
  13. How to store property file as xml file?
  14. How to get file last modified time?
  15. How to convert byte array to inputstream?
  16. How to convert inputstream to reader or BufferedReader?
  17. How to convert byte array to reader or BufferedReader?
  18. How to set file permissions in java?
  19. How to read a file using BufferedInputStream?
  20. How to create temporary file in java?
  21. How to write or store data into temporary file in java?
  22. How to delete temporary file in java?
  23. How to write string content to a file in java?
  24. How to write byte content to a file in java?

ServletOutputStream: ServletResponse.getOutputStream() returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data, it sends the raw data as it is.

PrintWriter: ServletResponse.getWriter() returns PrintWriter object which sends character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response’s character encoding has not been specified then it does default character encoding.

About Author

I’m Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected] .

Most Visited Pages

Источник

Оцените статью