serializing a list of objects into a file in java - java

I have a list of around 20,000 object, which in turn have a very huge hierarchy. I need to dump the objects into a file, so that i can read it later anytime during my process. Now my problem is, I have worked on Java but not that much on serialization and i dont have that much of knowledge how to do that.
In this case as far as i know, i need to use both Serialization ane De-Serialization. Can anyone please help. Also i can use any new API or normal Java Serialization.
Regards.

Look at this link http://www.java2s.com/Code/Java/File-Input-Output/Objectserialization.htm
Its something like this:
Card3 card = new Card3(12, Card3.SPADES);
System.out.println("Card to write is: " + card);
try {
FileOutputStream out = new FileOutputStream("card.out");
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(card);
oos.flush();
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
Card3 acard = null;
try {
FileInputStream in = new FileInputStream("card.out");
ObjectInputStream ois = new ObjectInputStream(in);
acard = (Card3) (ois.readObject());
} catch (Exception e) {
System.out.println("Problem serializing: " + e);
}
System.out.println("Card read is: " + acard);
Don't forget to implement Serializable interface in all class you want to save
and put modifier "transient" at all fields you don't want to save.
(e.g. private transient List cache;)

Rather than saving every object individually you can directly save the list of objects. I am using below code to achieve this. Although I am serializing for cloning, it should be sufficient to learn the basics.
public static List<EmpoyeeTO> deepCloneList( List<EmpoyeeTO> objectList) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(objectList);
oos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (List<EmpoyeeTO>) ois.readObject();
}catch(EOFException eof){
return objectList;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}

JSON is all the rage recently so you can use that. Jackson is a nice api for JSON serialization/deserialization. As a bonus you get interoperability with other platforms.
If you're not affraid of xml use JAXB
Of course you can always use binary serialization, but IMO text is easier to manage than blobs.

below is the code to write objects to file using XMLEncoder, assuming that your object implements Serializable Interface.
FileOutputStream os =new FileOutputStream("c:/temp/serialized.xml");
XMLEncoder encoder=new XMLEncoder(os);
encoder.writeObject(objectToBeSerialized);
encoder.close();
Below is the code to deserializ the Data
FileInputStream is=new FileInputStream("c:/temp/serialized.xml");
XMLDecoder decoder=new XMLDecoder(is);
Object object=(Object)decoder.readObject();
decoder.close();

I give you a sample
import java.io.Serializable;
public class Account implements Serializable {
private int accountNo;
private String custName;
private int balance;
/** Creates a new instance of Account */
public Account(int accNo, String name, int bal) {
this.accountNo = accNo;
this.custName = name;
this.balance = bal;
}
#Override
public String toString() {
String str = "Account No:" + this.accountNo;
str += "\nCustomer name:" + this.custName;
str += "\nBalance:" + this.balance;
return str;
}
}
Write and read object
package me.dev;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public void writeObject(ArrayList<Object> listAccount) throws IOException {
//Create FileOutputStream to write file
FileOutputStream fos = new FileOutputStream("C:\\bank.datum");
//Create ObjectOutputStream to write object
ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
//Write object to file
for (Object obj : listAccount) {
objOutputStream.writeObject(obj);
objOutputStream.reset();
}
objOutputStream.close();
}
public ArrayList<Account> readObject() throws ClassNotFoundException, IOException {
ArrayList<Account> listAccount = new ArrayList();
//Create new FileInputStream object to read file
FileInputStream fis = new FileInputStream("C:\\bank.datum");
//Create new ObjectInputStream object to read object from file
ObjectInputStream obj = new ObjectInputStream(fis);
try {
while (fis.available() != -1) {
//Read object from file
Account acc = (Account) obj.readObject();
listAccount.add(acc);
}
} catch (EOFException ex) {
//ex.printStackTrace();
}
return listAccount;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException {
try {
// TODO code application logic here
ArrayList<Object> listAcc = new ArrayList<Object>();
listAcc.add(new Account(1, "John", 1000));
listAcc.add(new Account(2, "Smith", 2000));
listAcc.add(new Account(3, "Tom", 3000));
Main main = new Main();
main.writeObject(listAcc);
ArrayList<Account> listAccount = main.readObject();
System.out.println("listisze:" + listAccount.size());
if (listAccount.size() > 0) {
for (Account account : listAccount) {
System.out.println(((Account) account).toString());
}
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Related

Reading objects from text file

I have a text file with serialized objects written it. The file contains data like this -
line[com.high.3449%]
line[com.high.58850?]
line[com.high.47646%]
I want to read this and store 1 by 1 in an arraylist. But when I read it I am just able to read the first line which is line[com.high.3449%] but not everything. I am using below logic to read -
List<MyData> myobjects1 = new ArrayList<MyData>();
List<MyData> myobjects2 = new ArrayList<MyData>();
FileInputStream fin = new FileInputStream("/storage/200B-431F/Documents/MyData.txt");
ois = new ObjectInputStream(fin);
try {
myobjects1 = (List<MyData>) ois.readObject();
while (myobjects1 != null) {
myobjects2.addAll(myobjects1);
Log.d("hi", "second arraylist " + myobjects2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois.close();
server.sendData(myobjects2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {}
Can someone help me how to read all the data and store in the arraylist myobjects2?
The issue seems to be related to your loop when you read back the data. There is no need to loop (it will loop forever)
Instead of
myobjects1 = (List<MyData>) ois.readObject();
while (myobjects1 != null) {
myobjects2.addAll(myobjects1);
...
You should use
myobjects1 = (List<MyData>) ois.readObject();
if (myobjects1 != null) {
myobjects2.addAll(myobjects1);
}
If you want to loop through the myobjects you need to use something like
for (MyData myData : myobjects1) {
myobjects2.add(myData);
}
Am adding the code I used to test the answer.
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class LoadFileObject {
public static class MyData implements Serializable {
private String line, content;
public MyData(String line, String content) {
setLine(line);
setContent(content);
}
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content= content;
}
public String toString() {
return (line+content);
}
}
#Test
public void doWork() throws Exception {
List<MyData> myobjects1 = new ArrayList<MyData>();
myobjects1.add(new MyData("l1", "content1"));
myobjects1.add(new MyData("l2", "content2"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("mydata.txt"));
oos.writeObject(myobjects1);
oos.close();
List<MyData> myobjects2 = new ArrayList<MyData>();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("mydata.txt"));
myobjects2 = (List<MyData>) ois.readObject();
System.out.println("read:" + myobjects2.size());
for (MyData myData : myobjects2) {
System.out.println("myData line:" + myData.getLine() + " content:" + myData.getContent());
}
}
}
try this :
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("/storage/200B-431F/Documents/MyData.txt/CPU.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
// here line variable will hold the data for each line of your text file
// i.e you can add the string to the arrayList here
myObjects2.add(line);
}
} catch (FileNotFoundException ex) {
}
catch (IOException ex) {
}

Serialization of an arraylist which contains another arraylist

my research on google-search and stackoverflow regarding this problem didn't resolve it.
i'd like to show you a snipped of my Datastructure:
there's a class, called "SequenceHolder" => this one carries an:
ArrayList<SequenceData> data;
within the Sequenceholder, there is a function to call the serialization:
public void writeSequenceList() throws FileNotFoundException, IOException {
FileOutputStream fout = new FileOutputStream(path);
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(data);
oout.close();
fout.close();
}
The class SequenceObject has following fields: (this one is on the top, where i start the serialization)
private ArrayList<SequenceModel> recordedSequenceData;
private String sequenceUrl;
while the SequenceModel is defined like this:
private Object sequenceRawData;
private boolean isProcessedByRequest;
The sequenceRawdata objects are basically two other classes (containing Strings only)!
every class of this "trail" implements the interface "Serializable".
this is the deserialization:
public ArrayList<SequenceData> loadSequenceList() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.data = (ArrayList<SequenceData>) in.readObject();
in.close();
fileIn.close();
return data; // load from de-serialization
}
after a deserialization of the SequenceObject, i'll only retrieve the "sequenceUrl", but no recordedSequenceData.
Is there a trick to do this?!
It came just up to my mind, to extend some classes with the ObjectOutputStream and call the writingprocess with "this" explicitly in every class - but yeah, i am not sure if thats a good idead.
What do you mean by "The sequenceRawdata objects are basically two other classes (containing Strings only)!" because when I try to run the same program :
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;
import java.io.Serializable;
import java.util.ArrayList;
class SequenceModel implements Serializable
{
public SequenceModel(Object a, boolean b)
{
sequenceRawData = a;
isProcessedByRequest = b;
}
public String toString()
{
return (String)sequenceRawData + isProcessedByRequest + " SeqModel ";
}
private Object sequenceRawData;
private boolean isProcessedByRequest;
}
class SequenceData implements Serializable
{
public SequenceData(ArrayList<SequenceModel> a, String b)
{
recordedSequenceData = a;
sequenceUrl = b;
}
public String toString()
{
return recordedSequenceData + sequenceUrl + " SeqData ";
}
private ArrayList<SequenceModel> recordedSequenceData;
private String sequenceUrl;
}
class SequenceHolder implements Serializable
{
ArrayList<SequenceData> data;
public String toString()
{
return data + " SeqHol ";
}
public SequenceHolder(ArrayList<SequenceData> a)
{
data = a;
}
public void writeSequenceList() throws FileNotFoundException, IOException {
FileOutputStream fout = new FileOutputStream(Test.file);
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(data);
oout.close();
fout.close();
}
public ArrayList<SequenceData> loadSequenceList() throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fileIn = new FileInputStream(Test.file);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.data = (ArrayList<SequenceData>) in.readObject();
in.close();
fileIn.close();
return data; // load from de-serialization
}
}
public class Test
{
public static File file = new File("abc.txt");
public static void main(String[] args)
{
SequenceModel obj = new SequenceModel("abc", false);
ArrayList list = new ArrayList(); list.add(obj);
SequenceData obh = new SequenceData(list, "str");
ArrayList l2 = new ArrayList();
l2.add(obh);
SequenceHolder obi = new SequenceHolder(l2);
try {
obi.writeSequenceList();
System.out.println(obi.loadSequenceList());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
it is able to serialize and deserialize both and there is no problem.
Output it is printing is : [[abcfalse SeqModel ]str SeqData ] which includes everything as desired.
Please let me know if I am missing anything.

What are the errors of this Java code?

package example;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Object;
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public class mytest {
public static void main(String[] args) throws IOException {
clone
}
}
For above code, it wants to show the deep copy of Java. But myeclipse reports some errors. But I don't know what is wrong with it?
Could anyone please help to point them out?
Changed the code according to your suggestion.
package example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.Object;
class Utils {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
public class mytest {
public static void main(String[] args) throws IOException {
Object clonedObject = Utils.copy(new Object());
clonedObject.notifyAll();
}
}
Further:
Thank you all!
I modifeid the code like above, it becomes better but still cannot run normally.
The new error message is below:
Any new suggestion?
You can't have floating methods in Java. Everything must be a member of a class. In this instance, a dummy class with only static methods called Utils would be common practice.
e.g.
public class Utils {
// Static methods go here
public static Object copy(Object oldObj) {
// etc
}
}
Then you can call it like so:
public class mytest {
public static void main(String[] args) throws IOException {
Object clonedObject = Utils.copy(new Object());
// etc
}
}
Here are the following steps to solve your errors:
Make a package inside a Project(Specific Name)
Inside a created package make a name MyTest.
Write or copy the method into that class which has been created
above.
To Run the Program Make one main Method any call it by there name if
it is static.
If your method is not static make a object of the class and call by
that object of the class.
It will solve your Error & also run your program...
Note: Try to put finally block to free the resources like object, ByteArrayOutputStream & ObjectStream etc.... It will increase your performance of the program.
You need to put a method into a class.
public class SomeClass{
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
And you can use it as:
public class mytest {
public static void main(String[] args) throws IOException {
Object object = Someclass.copy(someObject);
}
}
You can't declare methods (even static ones) outside of a class in Java. You would have to put everything (except the imports) inside a class.
You'll need something like:
public class YourClass {
public static Object copy(Object oldObj) {
...
}
}
The method public static Object copy(Object oldObj) isn't located in a class. That's why you are getting the error.
You must add a class named mytest as the 'top level scope' of this file, nest all other methods in it.
class mytest {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public class mytest {
public static void main(String[] args) throws IOException {
clone
}
}
}
As a side note, you should rename the class name (and file name) to MyTest and MyTest.java - to match the java coding convention.
You should put your method in a class, preferably called mytest since it's the name of the file, declared like
public class mytest {
//Your method here
}
Also note that the naming convention in Java is to have class names starting with a capital letter, so it would be MyTest, and your file should be renamed to reflect that.
Try
public class MyTest {
public static Object copy(Object oldObj) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
public static void main(String[] args) throws IOException {
clone
}
}
There are no methods who do not belong to a class (like a JavaScript-Function).
Static means that the method does belong to the class and not to an instance of the class as a non static method would do
You can't write methods outside the class. Put your method #copy inside the class. like this:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class mytest
{
public static void main(String[] args) throws IOException
{
// Now you can use your method here
}
public static Object copy(Object oldObj)
{
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(oldObj);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
Where is the class here? these method should contain a class.
Your java class should looks like this
package name;
imports;
public class MyClass{
public void myMethod(){
}
}

How to read/write an object that has linked lists in a file

I have these classes: "MyClass1", "MyClass2", "MyClass3" and "MyMainClass",
public class MyMainClass implements Serializable {
private String att1, att2, att3;
private int att4, att5, att6;
private LinkedList <MyClass1> myClass1List = new LinkedList<MyClass1>();
private LinkedList <MyClass2> myClass2List = new LinkedList<MyClass2>();
private LinkedList <MyClass3> myClass3List = new LinkedList<MyClass3>();
}
My program create registers (Objects) of "MyMainClass" and deposit it in a LinkedList. I want to save the LinkedList of the objects in a file to get them after i reopen my program. What's the way to do it? I have tried with ObjectOutputStream, but doesn't work. Thanks.
Edit:
My code to add an object(I just read an example and tried):
public static void addObject (MyMainClass p) {
try {
outputStream = new ObjectOutputStream(new FileOutputStream("myfile.dat"));
outputStream.writeObject(p);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
System.exit(1);
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
Note: "MyClass1", "MyClass2", "MyClass3" are Serializable.
I would make "myClass1", "myClass2", and "myClass3" Serializable, then wrap myClass1List, myClass2List, and myClass3List (and any other data you want to save) in another serializable class so you can use serialization/deserialization to save and restore all of the program state at once.
Unless myMainClass is that wrapper, in which case you need to declare that they all implement Serializable.
myMainClass isn't marked Serializable. Also, are myClass1, myClass2, and myClass3 serializable as well? If not, they should be.
On another note, please follow Java naming conventions; class name should start with an uppercase letter.
UPDATE
Are you sure that it's not writing to the file, or is it that the code is throwing exceptions that you cannot see?
In all your catch blocks, you have System.exit(1), which gives you absolutely no information about any exceptions that are happening; you're essentially swallowing them. You should at least print out the stacktrace (ex.printStackTrace()) so you can see what is going wrong.
I used following for my highschool project long time ago. Due to my poor English skills I do not really understand what class you wish to save and load (LinkedList or myMainClass), but I used this solution to successfully store and load any of my custom objects. I hope you find it handy.
Usage:
myMainClass object;
//
// ... your code fillin up the content of object
//
MyIO io = new MyIO();
io.save("", "myfile.dat", object); // "" as first argument will make java use current working directory
// to load the object:
myMainObject object = (myMainObject) io.load("", "myfile.dat");
Source:
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class MyIO {
// String path - path to the directory where the file is supposed to be saved.
// String filename - the name of the file
// Object data - object that you wish to save in the file. In your case "myMainClass"
public void save(String path, String filename, Object data) {
try {
FileOutputStream fos = new FileOutputStream(path + filename, false);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(data);
out.flush();
out.close();
} catch (IOException e) {
System.out.println(e);
}
}
// String path - path to the directory where the file is stored
// String filename - the name of the file
// The function returns java object which can be cast to myMainClass.
public Object load(String path, String filename) {
try {
FileInputStream fis = new FileInputStream(path + filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
Object data = in.readObject();
in.close();
return data;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
}

Is it possible to print out a Student object using RandomAccessFile?

I'm using RandomAccessFile to create a database to a text file. Basically I created a normal store using an ArrayList and now i need to output the contents of the store using RandomAccessFile. But I am stuck on how to get the randomAccessFile method to take the student store. Here is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
public class MainApp
{
private RandomAccessFile File;
public static void main(String[] args) throws Exception
{
new MainApp().start();
}
public void start()throws Exception
{
StudentStore details = new StudentStore();
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini#gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez#webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez#yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123#hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
details.print();
//Create a file object.
File contactDetailsFile = new File("StudentDetails.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(contactDetailsFile)));
out.println(a);
out.println(b);
out.println(c);
out.println(d);
out.println(e);
out.close();
BufferedReader in = new BufferedReader(
new FileReader(contactDetailsFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
/**
* #param args the command line arguments
*/
public void RandomAccessFile(String filename)
{
RandomAccessFile randomAccessFile = null;
try {
//Declare variables that we're going to write
String line1 = "First line\n";
String line2 = "Second line\n";
//Create RandomAccessFile instance with read / write permissions
randomAccessFile = new RandomAccessFile(filename, "rw");
//Write two lines to the file
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
//Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
//Declare a buffer with the same length as the second line
byte[] buffer = new byte[line2.length()];
//Read data from the file
randomAccessFile.read(buffer);
//Print out the buffer contents
System.out.println(new String(buffer));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
In a word, yes.
You will, however, have to re-do your write-to-file part of this solution again. You must read objects back out the same way you wrote them.
From this example, you can see how each member is written using the RandomAccessFile object.
I would suggest that you make the read method from the example return a new Student object.

Categories

Resources