Gson stream closing - java

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.

Related

Save java object to internal memory asynchroneously?

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.

Write/Read arrays in files android

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.

Closing Java Input/Output streams

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.

IOUtils.write creates new file but doesn't write data

using IOUtils.write to write a string to a file
try {
IOUtils.write("test", new FileWriter(configFile));
} catch (Exception e) {
e.printStackTrace();
}
where configfile is the location of the configuration file ("./resources/config.json")
This seems to delete the file and replace it with a file that has no contents.
no exceptions are thrown either.
Make sure to close the stream after use, else the data might not be written to the file.
FileWriter fw=null;
try {
fw= new FileWriter(configFile);
IOUtils.write("test",fw);
}catch (Exception e) {
e.printStackTrace();
}finally
{
IOUtils.closeQuietly(fw);
}
You need to close the writer, or use try with resources. Otherwise everything might not be flushed to disk:
try (FileWriter fw = new FileWriter(configFile)) {
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
}
Try this code:
FileWriter fw = null;
try {
fw = new FileWriter(configFile);
IOUtils.write("test", fw);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fw != null)
fw.close();
}

How should I deal with the exception which happened in a catch block?

BufferedReader in
= new BufferedReader(new FileReader(file));
try {
while((thisLine=in.readLine())!=null){
...
}
} catch (IOException e) {
//in.close();
// TODO Auto-generated catch block
e.printStackTrace();
}
in the code above, I want to close the read buffer in the catch block.But I find that the function in.close also throws an IOException. It look ugly if I nest another try-catch block in the catch block.So ,what is the correct way to deal with such a problem?
You can use finally block for that. finally-block execulated every time unless jvm exits abnormaly.
Java 7 try-with-resources statement to automatically close, you need to close resouce stream explicitly,
The try-with-resources statement is a try statement that declares one
or more resources. A resource is an object that must be closed after
the program is finished with it. The try-with-resources statement
ensures that each resource is closed at the end of the statement. Any
object that implements java.lang.AutoCloseable, which includes all
objects which implement java.io.Closeable, can be used as a resource.
read more on documentaion
Example -
try(BufferedReader in
= new BufferedReader(new FileReader(file))){
while((thisLine=in.readLine())!=null){
...
}
}catch (IOException e) {
...
}
Close the resources in a finally block, not in a catch block.
try
{
// actual code.
}
catch (IOException e) {
// handle exception
}
finally
{
try
{
in.close();
}
catch (IOException e) {
// handle exception
}
}
Do in finally block,Which is specially meant for cleanup.
From finally block docs
The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.
BufferedReader in
= new BufferedReader(new FileReader(file));
try {
while((thisLine=in.readLine())!=null){
...
}
} catch (IOException e) {
//in.close();
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
in.close
}
try {
in = new BufferedReader(new FileReader(file));
// stuff here
} finally {
try {
in.close()
} catch (IOException e) {} // ignore
}

Categories

Resources