Found the solution: you have to open the Streams like this:
FileInputStream inputStream = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(inputStream);
Same with Output. This fixed it for me, should anyone stumble upon this in search for an answer.
Original question:
Through a few tests with Toast
s I have found that when I call the Constructor for ObjectOutputStream
I get an IOException
thrown.
My code looks like this. Note that this is merely a test project, and I can't even get this one to work.
Button b = new Button(this);
b.setText("write");
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
File f = new File("Filepath");
if (!f.exists()) {
f.createNewFile();
}
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(f)); //IOException here!
Series x = new Series("Test", 20, 12);
// oos.writeObject(x);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
tv = new TextView(this);
tv.setText("Not read anything yet!");
Button r = new Button(this);
r.setText("Read");
r.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(new File("Filepath")));
Series y = (Series) ois.readObject();
tv.setText(y.getName() + "-" + y.getNumOfSeason() + "-"
+ y.getNumOfEpisode());
ois.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
The problem seems to be my constructor call. Before I added the part with
if (!f.exists()) {
f.createNewFile();
}
I got a FileNotFoundException
.
What am I doing wrong?
Found the solution: you have to open the Streams like this:
FileInputStream inputStream = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(inputStream);
Same with Output. This fixed it for me, should anyone stumble upon this in search for an answer.