When I load this file, I always get the NullPointerException. I try many thing and I could not find a way to fix it. When I saved I used the Game object.
#Override
public void load(Superhero aHero,Villain aVillain) throws IOException, ClassNotFoundException {
ObjectInputStream ois = null;
FileInputStream fis = null;
File f = new File("C:\\prog24178\\dcgames.dat");
Game aGame = new Game(aHero,aVillain);
try {
fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
while(true){
aGame = (Game) ois.readObject();
System.out.println(aGame);
}
} catch(EOFException eof){
ois.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(DcGameController.class.getName()).log(Level.SEVERE, null, ex);
}
}
When I open the file I see something like that:
’ sr
model.Game ^r Z gameOverZ heroTurnL theHerot Lmodel/Superhero;L
theVillaint Lmodel/Villain;xp sr model.hero.Batman ^r Z armedL sidekickq ~ xr model.Superhero ^r I energyZ secretIdentityL codenamet Ljava/lang/String;L hometownq ~ xr model.Avatar ^r
I agilityI enduranceI fightingI hitPointsI intuitionI psycheI reasonI strengthL firstNameq ~ L lastNameq ~ xp W t q ~ t Batmant Gotham Citysq ~ t Dickt Grayson ppsr model.villain.Cheetah ^r xr
model.Villain ^r I energyZ insaneL codenameq ~ xq ~ b t Priscillat Rich t Cheetah
So I know it's working but I would like to read and after that I could set the setting I need to use.
That's my save method :
#Override
public void saveGame(Game aGame) {
File aSaveFile = new File("C:\\prog24178\\dcgames.dat");
FileOutputStream fos = null;
if (!aSaveFile.getParentFile().exists()) {
aSaveFile.getParentFile().mkdir();
}
try {
if (!aSaveFile.exists()) {
aSaveFile.createNewFile();
}
if (aSaveFile.length() > 0) {
fos = new FileOutputStream(aSaveFile, true);
} else {
fos = new FileOutputStream(aSaveFile, false);
}
if (oos == null) {
oos = new ObjectOutputStream(fos);
}
oos.writeObject(aGame);
} catch (FileNotFoundException ex) {
} catch (Exception x) {
System.out.println("Something bad happened" + x);
}
}
Thanks for helping me to fix my issue.
I think there 2 problems u should check,
1.fos = new FileOutputStream(aSaveFile, true);
if aSaveFile already has some data and u append another object data to aSaveFile, its data will be confused, u'll not be able to bring the object back.
2.oos.writeObject(aGame);
when u finish writeObject(), u should flush the stream buffer using oos.flush();
Related
This is my method, he create new object "predmet". class "AddNewObject" return me predmet type (name, description).
AddNewPredmet addnewpredmet = new AddNewPredmet();
listPredmet.add(AddNewPredmet.AddPredmet());
StorageInFile.savePredmet(listPredmet);
All working. But I have a problem with the result written in the file. The output file has symbols that are not readable as shown -
¬н sr java.util.ArrayListxЃТ™Зaќ I sizexp w sr entity.PredmetїБц)Зя| L Descriptiont Ljava/lang/String;L PNameq ~ xpt testt testx
The following is the function that writes to the file
public class StorageInFile {
static void savePredmet(List<Predmet> listPredmet) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("Predmet.txt");
oos = new ObjectOutputStream(fos);
oos.writeObject(listPredmet);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Нет такого файла", ex);
} catch (IOException ex) {
Logger.getLogger(StorageInFile.class.getName())
.log(Level.SEVERE, "Не могу записать", ex);
}
}}
How i can fix this? I think about method toString(), but i cant add this method to this code.
Try using a buffered writer and use UTF-8 capable viewer to see the file. You are trying to using a tool that assumes a one-byte encoding, such as the Windows-125x encodings. Notepad is an example of such a tool. So using the capable viewer you can look at it.
Also it would help to show what’s in your file
If you expected to print the contents of every instance of Predmet in the List<> then you could try the following.
Implement to the toString() method in Class Predmet
Try the following snippet to write to file.
FileWriter writer = new FileWriter("sample.txt");
try {
int size = listPredMet.size();
for (int index =0; index < size; index++){
writer.write(listPredMet.get(index).toString());
writer.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally{
writer.close()
}
This question already has answers here:
EOFException when reading files with ObjectInputStream [duplicate]
(5 answers)
Closed 5 years ago.
I want write object to file and read them, but I'm getting error. Line 51 in Main.java is while loop which should display objects.
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2626)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1321)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
at com.sdajava.rwobj.Main.main(Main.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
My code: write object first and read them. The data is write to a file.
String fileName = "c://Users//lukas//obj.txt";
Person p1 = new Person("Jan", "Kowalski", 21);
Person p2 = new Person("Jan", "Kowalski", 21);
OutputStream fileOutputStream = null;
ObjectOutput objectOutputStream = null;
OutputStream bufferOut = null;
try {
fileOutputStream = new FileOutputStream(fileName);
bufferOut = new BufferedOutputStream(fileOutputStream);
objectOutputStream = new ObjectOutputStream(bufferOut);
objectOutputStream.writeObject(p1);
objectOutputStream.writeObject(p2);
objectOutputStream.close();
} finally {
if (objectOutputStream != null) {
objectOutputStream.close();
}
fileOutputStream.close();
bufferOut.close();
objectOutputStream.close();
}
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStream bufferIn = new BufferedInputStream(fileInputStream);
ObjectInputStream objectInputStream
= new ObjectInputStream(bufferIn);
Person readCase = null;
List<Person> recordList = new ArrayList<>();
do {
readCase = (Person) objectInputStream.readObject();
if (readCase != null) {
recordList.add(readCase);
}
} while (readCase != null);
fileOutputStream.close();
objectOutputStream.close();
} catch (FileNotFoundException err){
err.printStackTrace();
}
What is wrong?
do {
readCase = (Person) objectInputStream.readObject();
if (readCase != null) {
recordList.add(readCase);
}
} while (readCase != null);
This loop is not correct. readObject() does not return null at end of stream. It can do that any time you wrote a null. At end of stream it throws EOFException. So:
for (;;) {
try {
readCase = (Person) objectInputStream.readObject();
recordList.add(readCase);
}
catch (EOFException exc) {
break;
}
}
As pointed out in the comments you are trying to read more objects then stored, Also if in case you don't know already the number of objects stored, you can try it this way:
try{
while(true)
recordList.add((Person) objectInputStream.readObject());
}
catch(EOFException ex){
//All objects are read when control is here
}
I started developing an app for my class, which has a request that I need to save objects from a list in a .txt file. It seems to be working, but when I do that, it saves only one object that I entered. I don't know what the solution is. My code is below. P.S. I am using gui to add my objects in a list.
List<Korisnik> listaK=Kontroler.vratiObjekatKontroler().vratiKorisnika();
try {
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
ObjectOutputStream out= new ObjectOutputStream(fos);
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
out.close();
}
You are closing the output stream once you have written the first object. This way you cannot write anything else into it. Move the out.close() out of for loop.
You are closing your stream inside the for loop. I recommend:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(new File("output.txt"));
out= new ObjectOutputStream(fos);
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (out != null) out.close;
if (fos != null) fos.close;
}
Hoping that you are using at least Java SE 7 :) you can take advantage of try-with-resources so you don't need to care about closing "resources":
try (
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
ObjectOutputStream out= new ObjectOutputStream(fos)
){
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
}
The try-with-resources statement contains the FileOutputStream and ObjectOutputStream object declarations that are separated by a semicolon. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the FileOutputStream and ObjectOutputStream objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.
I am trying to add serilization and deserialization to my app. I have already added serization which makes it into a textfileThis problem is involving ArrayLists. I was browsing this page: http://www.vogella.com/articles/JavaSerialization/article.html when I saw this code:
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (Person) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
I was confused on this line:
p = (Person) in.readObject();
How do I make this line an ArrayList when creating an ArrayList is not as simple as that:
List<String> List = new ArrayList<String>();
Thanks for the help in advance!
I took the code directly from the website that you provided a link for and modified it for an ArrayList. You mention "How do I make this line an ArrayList when creating an ArrayList is not as simple as that", I say creating an ArrayList is as simple as that.
public static void main(String[] args) {
String filename = "c:\\time.ser";
ArrayList<String> p = new ArrayList<String>();
p.add("String1");
p.add("String2");
// Save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(p);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// Read the object from file
// Save the object to file
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (ArrayList<String>) in.readObject();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(p);
}
prints out [String1, String2]
Have you written a whole ArrayList as an object in the file?
Or have you written Persons object that were in an ArrayList in a loop in the file?
i want to write something with this code but after i run there are white spaces between characters. but in code i dont give space to string.
import java.io.*;
public class WriteText{
public static void main(String[] args) {
FileOutputStream fos;
DataOutputStream dos;
try {
File file= new File("C:\\JavaWorks\\gui\\bin\\hakki\\out.txt");
fos = new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeChars("Hello World!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output is (in text file) : H e l l o W o r l d !
Use writeBytes
dos.writeBytes("Hello World!");
Essentially, writeChars will write every character as 2 bytes. The second one you are seeing as extra spaces.
You could also use a FileWriter and a BufferedWritter instead; don't forget to close your buffer or dos when you're done with it.
FileWriter file;
BufferedWriter bw = null;
try {
file = new FileWriter("C:\\JavaWorks\\gui\\bin\\hakki\\out.txt");
bw = new BufferedWriter(file);
bw.write("Hello World!");
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try{
bw.close();
}
catch(IOException e){
e.printStackTrace();
}
}