I am trying to write an Object of kind "HashMap" to a file & recover it when my program run again. But I faced with an EOFException when I try to read that object and the Object is not read from the file. I use the flush() & close() methods when I wrote the object for the FileOutputStream & ObjectOutputStream. Also I create OutputStream & InputStream together for my file.
here is my code:
DataOutputStream outToFile;
DataInputStream inFromFile;
ObjectOutputStream writeTableToFile;
ObjectInputStream readTableFromFile;
File tableFile;
public DNS(){
try {
tableFile = new File("table.txt");
outToFile = new DataOutputStream(new FileOutputStream(tableFile) );
writeTableToFile = new ObjectOutputStream(outToFile);
inFromFile = new DataInputStream(new FileInputStream(tableFile));
readTableFromFile = new ObjectInputStream(inFromFile);
HashMap table2 = (HashMap) readTableFromFile.readObject();
if (table2 == null)
table=new HashMap(100);
else
table = table2;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(EOFException e){
table=new HashMap(100);
}
catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
and here is code for writing object:
table.put(NameField.getText(), IPField.getText());
try {
//writeTableToFile.reset();
writeTableToFile.writeObject(table);
writeTableToFile.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
Regards,
sajad
The file seems to be incomplete. When I look at your code, you're creating the file table.txt and try to read it immediately afterwards.
This ctor:
new FileOutputStream(tableFile)
will overwrite the file. If your read it afterwards, it will be empty (except the header information from the OOS)
EOFException means that the file is incomplete. So it's either not flush()ed or not close()ed or an exception is swallowed somewhere.
Related
I'm trying to create a file called manager.txt and read it. If it is empty (which it is) it will call a method to add things into it but I keep getting EOFException. I know the file is empty but it's just a part of a programI'm working on. How to determine a file is empty without getting EOFException
try(ObjectOutputStream outManager = new ObjectOutputStream(new
FileOutputStream("manager.txt"))){
try(ObjectInputStream inManager = new ObjectInputStream(new
FileInputStream("manager.txt"))){
while(true){
manager.add((Manager)inManager.readObject());
if(manager.isEmpty()){
//A method to add
}
}catch(IOException e){
}
}catch (IOException e){
}
You can read from file as follows:
try (FileInputStream fis = new FileInputStream("manager.txt");
ObjectInputStream ois = new ObjectInputStream(fis);)
{
while (fis.available() > 0) {
Object obj = ois.readObject();
if (obj instanceof Manager) {
Manager manager = (Manager) obj;
System.out.println(manager);
}
}
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
Basically, what you are looking for is fis.available().
for now i´ve got this two arrays that i want to save in a file
int var[][] = new int var[6][3]
int var_2[][] = new int var[7][5];
So whats the best way to write this into a file?
I´ve seen some examples like this
try {
ObjectOutputStream objOut = new ObjectOutputStream(new
FileOutputStream("data.dat"));
objOut.writeObject(var_1);
objOut.writeObject(var_2);
objOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
Am i doing this right? And if i am, how then do i read it right to my variables?
You're doing it right in concept, but there's room for improvement. First, you should use the Android logging facility (android.util.Log) rather than e.printStackTrace(). Also, if your minSdkLevel is 19 or more, I recommend that you use the try-with-resources statement:
try (ObjectOutputStream objOut = new ObjectOutputStream(new
FileOutputStream("data.dat")))
{
objOut.writeObject(var_1);
objOut.writeObject(var_2);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not save data", e);
}
(LOG_TAG is just some String you define to identify your class's output.) If you can't use try-with-resources, I recommend using a finally clause to close the stream:
ObjectOutputStream objOut = null;
try {
objOut = new ObjectOutputStream(new FileOutputStream("data.dat"))
objOut.writeObject(var_1);
objOut.writeObject(var_2);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not save data", e);
} finally {
if (objOut != null) {
try {
objOut.close();
} catch (Exception e) {
Log.e(LOG_TAG, "Could not close output file", e);
}
}
}
This ensures that the output stream gets closed even if an exception is thrown in the calls to writeObject.
To read the data back in, just open an ObjectInputStream to the same file and read the data in the same order in which you wrote them.
This is my code:
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream(file);
dos = new DataOutputStream(fos);
.... writing to file ....
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I read that you only need to close DataOutpustStream and it will close all other streams, is this correct? Does it do any harm if i close FileOutputStream anyways? What is the best way to close streams?
No, it doesn't do any harm
You need to close them in the same order that you opened them - think of them as wrappers around each-other. If you create a FileOutputStream and then wrap that in a DataOutputStream, you should close the DataOutputStream first.
But you should use try-with-resources:
try (
final FileOutputStream fos = new FileOutputStream(file);
final DataOutputStream dos = new DataOutputStream(fos);
) {
....writing to file....
} catch (IOException e) {
e.printStackTrace();
}
And if you handle the two exceptions in the same way, you can catch the more general IOException only.
The best way to close streams is when you're using try-resource-blocks.
In most cases streams are closed in a cascading manner. For the answer you have to take a closer look into the API.
I'm trying to write a file and then read it again.
My write code:
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try
{
Object myObject;
fout = new FileOutputStream(new File("C:\\Foo","Bar.log"));
oos = new ObjectOutputStream(fout);
oos.writeObject(myObject);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
oos.close();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My reader:
FileInputStream input;
try {
input = new FileInputStream(new File("C:\\Foo\\Bar.log"));
MyFile parsedObject = MyFileFormat.MyFile.parseFrom(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But I'm getting this exception on the parser:
com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.
at com.google.protobuf.InvalidProtocolBufferException.invalidEndTag(InvalidProtocolBufferException.java:94)
Can anyone help?
You use java's ObjectOutputStream to serialize your object, but using some custom de-serialization with guava involved?
If you use ObjectOutputStream to write stuff, you should use ObjectInputStream to read it. Also, your example does not make any sense. You never initialize myObject variable in serialization snippet, this code will simply not compile.
I have a problem with reading objects from file Java.
file is anarraylist<projet>
This is the code of saving objects :
try {
FileOutputStream fileOut = new FileOutputStream("les projets.txt", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (projet a : file) {
out.writeObject(a);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
And this is the code of reading objects from file ::
try {
FileInputStream fileIn = new FileInputStream("les projets.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (in.available() > 0){
projet c = (projet) in.readObject();
b.add(c);
}
choisir = new JList(b.toArray());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Writing is working properly. The problem is the reading... it does not read any object (projet) What could be the problem?
As mentioned by EJP in comment and this SO post . if you are planning to write multiple objects in a single file you should write custom ObjectOutputStream , because the while writing second or nth object header information the file will get corrupt.
As suggested by EJP write as ArrayList , since ArrayList is already Serializable you should not have issue. as
out.writeObject(file) and read it back as ArrayList b = (ArrayList) in.readObject();
for some reason if you cant write it as ArrayList. create custome ObjectOutStream as
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
and change your writeObject as
try {
FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true);
MyObjectOutputStream out = new MyObjectOutputStream(fileOut );
for (projet a : file) {
out.writeObject(a);
}
out.close();
}
catch(Exception e)
{e.printStackTrace();
}
and change your readObject as
ObjectInputStream in = null;
try {
FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt");
in = new ObjectInputStream(fileIn );
while(true) {
try{
projet c = (projet) in.readObject();
b.add(c);
}catch(EOFException ex){
// end of file case
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}