I am trying to add serilization and deserialization to my app. I have already added serization which makes it into a textfileThis problem is involving ArrayLists. I was browsing this page: http://www.vogella.com/articles/JavaSerialization/article.html when I saw this code:
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (Person) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
I was confused on this line:
p = (Person) in.readObject();
How do I make this line an ArrayList when creating an ArrayList is not as simple as that:
List<String> List = new ArrayList<String>();
Thanks for the help in advance!
I took the code directly from the website that you provided a link for and modified it for an ArrayList. You mention "How do I make this line an ArrayList when creating an ArrayList is not as simple as that", I say creating an ArrayList is as simple as that.
public static void main(String[] args) {
String filename = "c:\\time.ser";
ArrayList<String> p = new ArrayList<String>();
p.add("String1");
p.add("String2");
// Save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(p);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// Read the object from file
// Save the object to file
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (ArrayList<String>) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
prints out [String1, String2]
Have you written a whole ArrayList as an object in the file?
Or have you written Persons object that were in an ArrayList in a loop in the file?
Related
With Java:
I have a byte[] that represents a file.
How do I write this to a file (ie. C:\myfile.pdf)
I know it's done with InputStream, but I can't seem to work it out.
Use Apache Commons IO
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Or, if you insist on making work for yourself...
try (FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(myByteArray);
//fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
Without any libraries:
try (FileOutputStream stream = new FileOutputStream(path)) {
stream.write(bytes);
}
With Google Guava:
Files.write(bytes, new File(path));
With Apache Commons:
FileUtils.writeByteArrayToFile(new File(path), bytes);
All of these strategies require that you catch an IOException at some point too.
Another solution using java.nio.file:
byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
Also since Java 7, one line with java.nio.file.Files:
Files.write(new File(filePath).toPath(), data);
Where data is your byte[] and filePath is a String. You can also add multiple file open options with the StandardOpenOptions class. Add throws or surround with try/catch.
From Java 7 onward you can use the try-with-resources statement to avoid leaking resources and make your code easier to read. More on that here.
To write your byteArray to a file you would do:
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
fos.write(byteArray);
} catch (IOException ioe) {
ioe.printStackTrace();
}
Try an OutputStream or more specifically FileOutputStream
Basic example:
String fileName = "file.test";
BufferedOutputStream bs = null;
try {
FileOutputStream fs = new FileOutputStream(new File(fileName));
bs = new BufferedOutputStream(fs);
bs.write(byte_array);
bs.close();
bs = null;
} catch (Exception e) {
e.printStackTrace()
}
if (bs != null) try { bs.close(); } catch (Exception e) {}
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
////////////////////////// 1] File to Byte [] ///////////////////
Path path = Paths.get(p);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException ex) {
Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
}
/////////////////////// 2] Byte [] to File ///////////////////////////
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
I know it's done with InputStream
Actually, you'd be writing to a file output...
This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.
`Enter code here
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//
public class ReadandWriteAByte {
public void readandWriteBytesToFile(){
File file = new File("count.char"); //(abcdefghijk)
File bfile = new File("bytefile.txt");//(New File)
byte[] b;
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream (file);
fos = new FileOutputStream (bfile);
b = new byte [1024];
int i;
StringBuilder sb = new StringBuilder();
while ((i = fis.read(b))!=-1){
sb.append(new String(b,5,5));
fos.write(b, 2, 5);
}
System.out.println(sb.toString());
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fis != null);
fis.close(); //This helps to close the stream
}catch (IOException e){
e.printStackTrace();
}
}
}
public static void main (String args[]){
ReadandWriteAByte rb = new ReadandWriteAByte();
rb.readandWriteBytesToFile();
}
}
O/P in console : fghij
O/P in new file :cdefg
You can try Cactoos:
new LengthOf(new TeeInput(array, new File("a.txt"))).value();
More details: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html
This question already has answers here:
EOFException when reading files with ObjectInputStream [duplicate]
(5 answers)
Closed 5 years ago.
I want write object to file and read them, but I'm getting error. Line 51 in Main.java is while loop which should display objects.
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2626)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1321)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at com.sdajava.rwobj.Main.main(Main.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
My code: write object first and read them. The data is write to a file.
String fileName = "c://Users//lukas//obj.txt";
Person p1 = new Person("Jan", "Kowalski", 21);
Person p2 = new Person("Jan", "Kowalski", 21);
OutputStream fileOutputStream = null;
ObjectOutput objectOutputStream = null;
OutputStream bufferOut = null;
try {
fileOutputStream = new FileOutputStream(fileName);
bufferOut = new BufferedOutputStream(fileOutputStream);
objectOutputStream = new ObjectOutputStream(bufferOut);
objectOutputStream.writeObject(p1);
objectOutputStream.writeObject(p2);
objectOutputStream.close();
} finally {
if (objectOutputStream != null) {
objectOutputStream.close();
}
fileOutputStream.close();
bufferOut.close();
objectOutputStream.close();
}
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStream bufferIn = new BufferedInputStream(fileInputStream);
ObjectInputStream objectInputStream
= new ObjectInputStream(bufferIn);
Person readCase = null;
List<Person> recordList = new ArrayList<>();
do {
readCase = (Person) objectInputStream.readObject();
if (readCase != null) {
recordList.add(readCase);
}
} while (readCase != null);
fileOutputStream.close();
objectOutputStream.close();
} catch (FileNotFoundException err){
err.printStackTrace();
}
What is wrong?
do {
readCase = (Person) objectInputStream.readObject();
if (readCase != null) {
recordList.add(readCase);
}
} while (readCase != null);
This loop is not correct. readObject() does not return null at end of stream. It can do that any time you wrote a null. At end of stream it throws EOFException. So:
for (;;) {
try {
readCase = (Person) objectInputStream.readObject();
recordList.add(readCase);
}
catch (EOFException exc) {
break;
}
}
As pointed out in the comments you are trying to read more objects then stored, Also if in case you don't know already the number of objects stored, you can try it this way:
try{
while(true)
recordList.add((Person) objectInputStream.readObject());
}
catch(EOFException ex){
//All objects are read when control is here
}
I'm trying to read a map of Students from a txt file, after that I add a new student to the map (now is bigger than before) and save it back to the file. After I close my program and reload the data from file, the new students weren't saved.
HashMap<String, Student> studentObj = new HashMap<>(SIZE);
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME));
studentObj = (HashMap<String, Student>) in.readObject();
studentObj.put(student.getStudentID(), student);
ObjectOutputStream out;
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(DEFAULT_FILE_NAME)));
out.writeObject(studentObj);
out.flush();
System.out.println("here " + studentObj.size());
in.close();
out.close();
} catch (IOException e) {
throw new Exception("FILE IS NOT CREATED");
} catch (ClassNotFoundException e) {
throw new Exception("CLASS NOT FOUND EXCPETION");
}
I agree with #xdevs23
Instead of saving the data into arrays (which will use more memory), you could write
/*import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;*/
HashMap<String, Student> studentObj = new HashMap<>(SIZE);
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(DEFAULT_FILE_NAME));
studentObj = (HashMap<String, Student>) in.readObject();
studentObj.put(student.getStudentID(), student);
in.close();
System.out.println("here " + studentObj.size());
FileOutputStream fos = new FileOutputStream(DEFAULT_FILE_NAME);
OutputStreamWriter osw = new OutputStreamWriter(fos);
Writer w = new BufferedWriter(osw);
// Iterate using YOUR hash keys
for(int i = 0; i < studentObj.size(); i++){
w.write(studentObj.get(i).getString());
w.write(studentObj.get(i).getStudent());
}
w.close();
catch (IOException e) {
throw new Exception("FILE IS NOT CREATED");
} catch (ClassNotFoundException e) {
throw new Exception("CLASS NOT FOUND EXCPETION");
}
}
And just write the data pulled from ObjectInputStream directly to the file
My code was ok. The problem was that after saving the object to the file, then I closed the app and opened it again. Then, the constructor created a new file that overrides the old one. I added an if statement to create the file just for the first time. I used txt to make it simple and fast because is just a small task. I love to use xml files instead :) And yes, JAVA can save objects.
I have a Hashtable<String, String>table contains data to be stored in a text file , I stored it as an Object like this way:
Hashtable<String, String>table1=new Hashtable<String,String>();
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(table1);
oos.close();
fos.close();
Then I tried to read it like an Object as I had stored it like this way:
Hashtable<String, String>table2=new Hashtable<String,String>();
FileInputStream reader=new FileInputStream(file);;
ObjectInputStream buffer=new ObjectInputStream(reader);
Object obj=buffer.readObject();
table2=(Hashtable<String, String>)obj;
buffer.close();
reader.close();
but the problem is table2 still null !! I think the problem is in the way of reading, please any useful way of reading ?
I suggest you use a HashMap<String, String> instead of Hashtable<String, String> and program to the Map<String,String> interface, I would also suggest you use try-with-resources, finally make sure to store something in your Collection before you serialize it.
File f = new File(System.getProperty("user.home"), "test.ser");
Map<String, String> table1 = new HashMap<>();
table1.put("Hello", "world");
try (FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(table1);
} catch (Exception e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);) {
Map<String, String> table = (Map<String, String>) ois.readObject();
System.out.println(table);
} catch (Exception e) {
e.printStackTrace();
}
Output is
{Hello=world}
I need to create a copy of an already existing tree , created using DefaultMutableTreeNode.[Edit]
So, I have tried to assign the existing root node, to another DefaultMutableTreeNode.Ex:
DefaultMutableTreeNode ABC = new DefaultMutableTreeNode(null);
DefaultMutableTreeNode ABCcopy = new DefaultMutableTreeNode(null);
ABCcopy=ABC;
But this didnt give me much results.
Please advice.
the easiest way to (deep) copy/clone an object in java is by serializing/deserializing it.
If you use your both trees just for displaying some hierarchical data and do not modify nodes, so the easiest way is this:
JTree new_tree = new JTree(old_tree.getModel());
If you plan to modify one of trees the best way would be to clone.
Here is an example:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream("somefilename");
out = new ObjectOutputStream(fos);
out.writeObject(ABC);
out.close();
} catch(IOException ex) {
ex.printStackTrace();
}
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream("somefilename");
in = new ObjectInputStream(fis);
ABCCopy = (DefaultMutableTreeNode)in.readObject();
in.close();
} catch(IOException ex) {
ex.printStackTrace();
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}
How about
Tree newTree = existingTree.clone() ?