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.
Related
Does the stream close when you use something like:
gson.toJson(obj, new FileWriter("C:\\fileName.json"));
or is it better to to this:
try (Reader reader = new FileReader("c:\\test\\staff.json")) {
// Convert JSON File to Java Object
Staff staff = gson.fromJson(reader, Staff.class);
// print staff
System.out.println(staff);
} catch (IOException e) {
e.printStackTrace();
}
I know the try block closes the stream, but does ths first example also close the stream?
Code taken from
Mkyong
Does the stream close when you use something like:
gson.toJson(obj, new FileWriter("C:\\fileName.json"));
It does not. You should close it using try-with-resources, or a try-catch-finally block.
Since JDK 7, the preferred way to close an AutoClosable is to use try-with-resources (like in your second snippet):
try (FileWriter writer = new FileWriter("C:\\fileName.json")) {
gson.toJson(obj, writer);
} catch (IOException e) {
e.printStackTrace();
}
Or you could call close() using a try-catch-finally block:
FileWriter writer = null;
try {
writer = new FileWriter("C:\\fileName.json");
gson.toJson(obj, writer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileWriter implements AutoClosable so it needs to be closed. Not naming the variable will not close it automatically.
I need to save a java object to internal memory (a high-level collection of different server responses if to be specific). Now I use this code:
public void write(Context context) {
FileOutputStream fos = null;
try {
fos = context.openFileOutput(BACKSTACK_FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) { e.printStackTrace(); }
try {
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(backStack);
} catch (IOException e) {
L.t("failed to write backstack: " + e.toString()); e.printStackTrace();
} finally {
try { if (fos != null) fos.close(); } catch (IOException e) { }
}
}
public void read(Context context) {
FileInputStream fis = null;
try {
fis = context.openFileInput(BACKSTACK_FILENAME);
} catch (FileNotFoundException e) { e.printStackTrace();}
try {
ObjectInputStream ois = new ObjectInputStream(fis);
Deque<FragmentInfo> list = (Deque<FragmentInfo>) ois.readObject();
L.t(list.toString());
backStack = list;
} catch (IOException | ClassNotFoundException e) {
L.t("failed to read backstack" + e.toString()); e.printStackTrace();
} finally {
try { if (fis != null) fis.close(); } catch (IOException e) { }
}
}
Since we have context here, UI thread hangs(lags) white operation is performed.
And the larger object becomes, the worse it looks. So the question is:
Is there any way to save java object to internal memory asynchroneously?
Please don't recommend to use a database for such a simple task.
Saving to internal memory won't help. The real problem is that you are doing too much work on the event listener thread. You will have the same problem if you save lots of stuff to a file, a database, "internal memory" .... or to anything else. Serialization is relatively expensive no matter how you do it, and no matter where you save the results of the serialization.
The solution is to do the work using an AsyncTask.
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.
Getting error NullPointerException while trying to identify if serialized object is available and receive it using socket. How to identify if ObjectInputStream has available object?
Firs off I try to read a text then try to read from the same socket Lot object ()which may not be there.
public class ThreadIn extends Thread{
BufferedReader in;
PrintStream outConsole;
Socket socket;
ObjectInputStream ois;
String str;
Lot lot;
ThreadIn(BufferedReader input, PrintStream inOutput, Socket s){
str = "";
in= input;
socket= s;
try {
ois = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
outConsole = inOutput;
}
public void run() {
while(!EXIT_THREAD){
try {
if(in.ready()){
try {
str= in.readLine();
Thread.sleep(100);
} catch (IOException e) {
EXIT_THREAD= true;
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
outConsole.println("Received:"+str);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if((Lot)ois.readObject() != null){
lot = (Lot)ois.readObject();
if (lot!=null){outConsole.println(lot.toString());}
outConsole.println((String)ois.readObject());
}
} catch (Exception e) {
e.printStackTrace();
}
}
if((Lot)ois.readObject() != null)
this part itself reads the object from Socket., So you are reading 3 times the object from Socket in your code. If you have only one Object coming in the socket, or more, you can read the object and catch the exception!.
Just like below
//..loop start
try {
lot = (Lot)ois.readObject();
}
catch (Exception e)
{
// do some handling, skip the object! put a continue: or something
}
//do what ever you want to do with `lot`
//..loop end
and now, as per your code, you have not initialized your ObjectInputStream Object.
Do a ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
If you omitted the code here, well my mistake, else pls do initialize the socket also!
As per the other answers, including the deleted ones, you are calling readObject() twice and throwing the first result away. You should reorganize your code so it can block in readObject().
You have other problems. You are testing the result of readObject() for null?, but it only returns null if you wrote a null at the sender. I suspect you are using this as an EOS test, but it is invalid. readObject() throws EOFException at EOS. You should reorganize your code so it can block in readObject().
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.