Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
When reading a serialized object from a file, I get:
java.io.StreamCorruptedException: Wrong format: 0
The object, which implements Serializable is saved and restored as such:
Save:
try {
FileOutputStream fileOutputStream = getContext().openFileOutput("gameState.ser", Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(gameAssets);
} catch (Exception e) {
e.printStackTrace();
}
Restore:
try {
FileInputStream fileInputStream = getContext().openFileInput("gameState.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
gameAssets = (GameAssets) objectInputStream.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Since you haven't posted the surrounding code, I am not sure if this is the case, or the source of the error.
But you should always close your streams after writing to them.
Make sure all the fields on gameAssets are serializeable. If one of them is not an exception can be printed into the file you created which can cause an exception on read of that file.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
See the codes :
I usually do like below
RandomAccessFile raf = null;
try {
// do something ...
} catch (IOException e) {
// logger
} finally {
try {
if (null != raf) {
raf.close();
}
} catch (IOException e) {
// logger
}
}
Then I see I can do this in Java8
try (RandomAccessFile raf = ... ) {
// do something ...
} catch (IOException e) {
// logger
}
It seems a good way.
Looks like Java do the job to close IO.
edit 1
Personally, I like the 2nd way.
But is it good to use and has a high performance?
With Java 7 or higher, if the resource implements AutoCloseable, best practice is to use try-with-resources:
try (
RandomAccessFile raf = /*construct it */
) {
// Use it...
}
The resource will be closed automatically. (And yes, the catch and finally clauses are optional with try-with-resources.)
Regarding the code in your question:
Re the main catch block: "log and forget" is generally not best practice. Either don't catch the exception (so the caller can deal with it) or deal with it correctly.
In the catch block in your finally where you're closing, you're quite right not to allow that to throw (you could mask the main exception), but look at the way the spec defines try-with-resources and consider following that pattern, which includes any exception from close as a suppressed exception.
new JarFile(path) can trow an I/O exception.
If that happens, and I catch the exception, should I close it? (I guess the real question is, is there anything to close?)
The other question is: if it works, should I clean up? I.e., do the general rules for dealing with streams apply?
Sorry if the question is a bit naff; I'm new to dealing with JarFile (and haven't really used streams in the past, either).
There is nothing to close if new JarFile(path) throws an IOException:
JarFile file = null;
try {
file = new JarFile("does/not/exist");
} catch (IOException e) {
System.out.println(file); //Prints out null
}
try {
file.close(); //Throws NullPointerException
} catch (IOException e) {
e.printStackTrace();
}
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.
Here is my code. HELP ME!
String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
BufferedWriter out = new BufferedWriter(charectersname);
out.write(playername);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).
So you can do this:
out.close();
which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:
out.flush();
You'd likely want to do this when finishing up with such a resource. e.g.
BufferedWriter out = ...
try {
out.write(...);
}
catch (Exception e) {
// ..
}
finally {
out.close();
}
Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.
The Java 7 version with the try() closing automatically.
try (BufferedWriter out = new BufferedWriter(
new FileWriter("/Users/AlecStanton/Desktop/name.txt"))) {
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
}
Mind the left-out / after .txt.
You should close your writer in a finally block.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("/Users/AlecStanton/Desktop/name.txt/"));
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null){
out.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
I know that this type of question have been asked many times. But I didn't find any answer for myself. That's why i am asking once more.
I have got an output on my console. I want to copy the same output 1-to-1 to a file. I don't want to redirect. I want some kind of "copy" it and "write" into a file.
I hope the question is clear enough, cause I have seen that the other times, the question wasn't clear.
Anyways, I have tried it with the "System.setOut" methode. But it just redirect everything to the file.
I cannot write all the "System.out.println"s with a write() into a file, that to much.
Thanks for helping.
There is no way you can get console output. You have to do everything before printing
To Write our to a file do this.
try{
FileWriter x = new FileWriter(new File("x.txt"));
x.write("hello");
}catch(IOExecption e){
}
That will write out hello to a file
You could do something like this , the system out will happen after the log to file.
This code will append. Please This is NOT a good example of Exception handling, just an example of what you can do.
protected void writeToFileAndLog(String logEntry)
{
String file = "MyAmazingLog.txt";
try
{
FileOutputStream appendedFile = new FileOutputStream(file, true);
DataOutputStream out = new DataOutputStream(appendedFile);
out.writeBytes(String.format("%s\n", logEntry));
out.flush();
out.close();
System.out.println(logEntry);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.
Here is my code. HELP ME!
String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
BufferedWriter out = new BufferedWriter(charectersname);
out.write(playername);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).
So you can do this:
out.close();
which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:
out.flush();
You'd likely want to do this when finishing up with such a resource. e.g.
BufferedWriter out = ...
try {
out.write(...);
}
catch (Exception e) {
// ..
}
finally {
out.close();
}
Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.
The Java 7 version with the try() closing automatically.
try (BufferedWriter out = new BufferedWriter(
new FileWriter("/Users/AlecStanton/Desktop/name.txt"))) {
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
}
Mind the left-out / after .txt.
You should close your writer in a finally block.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("/Users/AlecStanton/Desktop/name.txt/"));
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null){
out.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}