How to Read entire file into character array in Java - File Handling in java
FileReader's read(char []) function allows you to load entire file into the character array.This program shows how to Read an entire file into character array in Java..
Student.java
public class Student implements Serializable{ int id; String name; public Student(int id, String name) { this.id = id; this.name = name; } public Student() { } public void display(){ System.out.println("ID: " + id); System.out.println("Name: " + name); } }
FileIO.java
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class FileIO{ public static void main(String[] args) { Student student = new Student(1, "Name 1"); student.display(); System.out.println("Serializing...\n"); serialize(student); System.out.println("Deserializing and reading into new object..."); System.out.println("Student#2 object"); Student student2 = new Student(); student2 = deserialize(student2); student2.display(); } private static Student deserialize(Student student2) { ObjectInputStream objectInputStream; try { objectInputStream = new ObjectInputStream(new FileInputStream("myFile.ser")); student2 = (Student) objectInputStream.readObject(); if (objectInputStream!=null) objectInputStream.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return student2; } private static void serialize(Student student) { //Serialize student information into file. ObjectOutputStream objectOutputStream; try { objectOutputStream = new ObjectOutputStream(new FileOutputStream("myFile.ser")); objectOutputStream.writeObject(student); if (objectOutputStream!=null) objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
No comments:
Post a Comment