I have created a save and a load function for my game,however, it refuses to load. (This is my first dealing with save/restore functionality).
It seems to save and by that i mean a 'minesweepersavestate.ser' file appears in my folder but there is an error loading, the error lies in the for (Enumeration e = b.keys(); e.hasMoreElements(); ) { line. It wont compile because it says 'cannot find sysmbol - method keys', i have imported java.util.*.
Could anyone tell me where my error is so i can get these functions working, thank you.
public void saveGame(){
GameBoard b = new GameBoard();
try {
System.out.println("Creating File/Object output stream...");
FileOutputStream fileOut = new FileOutputStream("minesweepersavestate.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
System.out.println("Writing GameBoard Object...");
out.writeObject(b);
System.out.println("Closing all output streams...\n");
out.close();
fileOut.close();
} catch(FileNotFoundException e) {
System.out.println("Class not found\n");
e.printStackTrace();
} catch (IOException e) {
System.out.println("no");
e.printStackTrace();
}
}
public void LoadBoard()
{
GameBoard b = null;
try {
System.out.println("Creating File/Object input stream...");
FileInputStream fileIn = new FileInputStream("minesweepersavestate.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println("Loading GameBoard Object...");
b = (GameBoard)in.readObject();
System.out.println("Closing all input streams...\n");
in.close();
fileIn.close();
} catch (ClassNotFoundException e) {
System.out.println("Class not found\n");
e.printStackTrace();
} catch(FileNotFoundException e) {
System.out.println("File not found\n");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Printing out loaded elements...");
for (Enumeration e = b.keys(); e.hasMoreElements(); ) {
Object obj = e.nextElement();
System.out.println(" - Element(" + obj + ") = " + b.get(obj));
}
Related
I create a client similarity, where clients register an account (an object is created) which is stored in a file.
Objects are written to the file as required, I override the writeStreamHeader() method. But when I try to read them all, their file throws an exception.
Write the objects to the file here.
public static void saveAccaunt(LoginAndPass gamers) {
boolean b = true;
FileInputStream fis = null;
try{
fis = new FileInputStream("student.ser");
fis.close();
}
catch (FileNotFoundException e)
{
b = false;
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream("student.ser",true);
ObjectOutputStream os = null;
if(b = true){
os = new AppendingObjectOutputStream(fileOutputStream);
System.out.println("Объект добавлен!");
}else {
os = new ObjectOutputStream(fileOutputStream);
System.out.println("Создан");
}
os.writeObject(gamers);
os.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("student.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
test = new ArrayList<>();
while (true){
test.add(objectInputStream.readObject());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(test.get(0));
}
Here is the error log for the exception thrown:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
at java.io.ObjectInputStream.(ObjectInputStream.java:358)
at Registratsiya.AllGamers.main(AllGamers.java:48)
Exception in thread "main" java.lang.NullPointerException
at Registratsiya.AllGamers.main(AllGamers.java:61)
In the code below how come when it say that it has successfully deleted the file, but when I check the file is still there. How would I remove the file. Basically I'm trying the delete the first file that I made after I was done using it to create the second file.
public static void main(String[] args) {
File file = new File("Hello");
try {
file.createNewFile();
} catch (Exception e) { }
try {
PrintWriter e = new PrintWriter(file);
e.println("Hello hi");
e.close();
}catch (Exception e) {}
File file2 = new File("Hello2");
try {
file2.createNewFile();
} catch (Exception e) {}
try {
Scanner x = new Scanner(file);
PrintWriter e = new PrintWriter(file);
while (x.hasNextLine()) {
System.out.println("Hello");}
e.close();
} catch (Exception e) {}
try {
file.delete();
System.out.println("It was deleted");
} catch (Exception e) { }
}
}
file.delete() doesn't throw an IOException, it returns a boolean check into if condition
if(file.delete())
{
System.out.println("File deleted successfully");
}
else
{
System.out.println("Failed to delete the file");
}
How create multiple serialization ? Now the system write just last record to txt. I want create simple DB that will contain customers info. And what you think, about this method of storing data in txt. ?
private static void WriteCustomers(){
System.out.println("|______Registration module______|");
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
CustomerManagement obj = new CustomerManagement();
CustomerManagementD customerManagementD = new CustomerManagementD();
customerManagementD.setFirstName(firstName);
customerManagementD.setLastName(lastName);
.....
obj.serializeCustomers(customerManagementD);
}catch (IOException e){
e.getMessage();
}
}
public void serializeCustomers(CustomerManagementD customerManagementD) {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
try {
fout = new FileOutputStream("CustomerManagement.txt");
oos = new ObjectOutputStream(fout);
oos.writeObject(customerManagementD);
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Last question, If I use serialization, I will be able to Edit and Remove stored particular objects?
A txt-file is used for text-only. The ObjectOutputStream stores more than then fields: it stores the classname (and serialVersionUID if present). Try to use .dat what is a generic extension for databases or datas.
You call the method serializeCustomers where Customers is plural and let me think we can store multiple Customer, but the parameter does not allow to use multiple customers. Instead, I suggest, to store a Set (like a LinkedHashSet) to store multiple customers, and yes, you can read and write to the LinkedHashSet.
SOLUTION
private static void WriteCustomers(List<CustomerManagementD> list){
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
// serialize collection of customers
customerManagementDArraysList.add(new CustomerManagementD(
customerID,firstName,lastName,email,contactNo));
ObjectOutputStream outStream = null;
try {
outStream = new ObjectOutputStream(new FileOutputStream(file));
for (CustomerManagementD p : list) {
outStream.writeObject(p);
}
} catch (IOException ioException) {
System.err.println("Error opening file.");
} finally {
try {
if (outStream != null)
outStream.close();
} catch (IOException ioException) {
System.err.println("Error closing file.");
}
}
}else if (finalcheck.equals("2")){
Adminswitch();
}
System.out.println("|______Customer was successfully saved______|\n Press 'Enter' to continue...");
String absentinput = reader.readLine();
Adminswitch();
}catch (IOException e){
e.printStackTrace();
}
}
private static ArrayList ViewCustomer(){
try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream oos =new ObjectInputStream(fis);
ArrayList<CustomerManagementD> customerManagementDArraysList = new ArrayList<>();
try {
while (true) {
CustomerManagementD cmd = (CustomerManagementD) oos.readObject();
customerManagementDArraysList.add(cmd);
}
}catch (EOFException e){
e.getMessage();
}
{
while (file.canRead()){
for (CustomerManagementD cmd : customerManagementDArraysList) {
System.out.println("Customer ID: " + cmd.getCustomerID() +
" First Name: " + cmd.getFirstName() +
" Last Name: " + cmd.getLastName()+....);
}
break;
}
}
}catch (IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();}
return null;
}
How does this code delete the file I had and makes a new one??
public void actualizaJTextArea(String cliente){
mensagens.setText("");
Scanner scanner = null;
File file = createFile(cliente + "chatswith.txt");
try {
scanner = new Scanner(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(...)
scanner.close();
}
public static File createFile(String s){
File file = new File(s);
if(!file.exists()){
try {
boolean b = file.createNewFile();
System.out.println(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
Does the method createNewFile() do this?
Thanks and I'm sorry if this has been asked before I just can't find it.
EDIT
I am also using createFile() in here to write in it but the use is the same so i guess that can't be it:
public void recebeMensagem(boolean b){
while(true){
Mensagem m = null;
try {
m = (Mensagem)input.readObject();
System.out.println("Mensagem Recebida:"+m);
} catch (ClassNotFoundException e){
} catch (IOException e) {
try {
input.close();
System.out.println("Server desligou...");
break;
} catch (IOException e1) {
}
}
if(m != null){
for(Mensagens mensagens:v){
for(String string: m.getReceivers()){
if (mensagens.getCliente().equals(m.getAuthor()) && mensagens.getContacto().equals(string)){
mensagens.actualizaJTextArea(cliente);
}
}
}
for(String Str :m.getReceivers()){
PrintWriter p = null;
File file = Mensagens.createFile(cliente + "chatswith.txt");
try {
p = new PrintWriter(new FileWriter(file));
p.append(m.getAuthor()+"</<"+Str+"</<"+m.getText()+"\n");
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
createNewFile() is atomic and it will not delete the file if it is present. Please look at the boolean output, it should be false if your file exists already.
EDIT
add append parameter to FileWriter. It is overwriting every time.
FROM
p = new PrintWriter(new FileWriter(file));
TO
p = new PrintWriter(new FileWriter(file,true));
I have a problem with reading objects from file Java.
file is anarraylist<projet>
This is the code of saving objects :
try {
FileOutputStream fileOut = new FileOutputStream("les projets.txt", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (projet a : file) {
out.writeObject(a);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
And this is the code of reading objects from file ::
try {
FileInputStream fileIn = new FileInputStream("les projets.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (in.available() > 0){
projet c = (projet) in.readObject();
b.add(c);
}
choisir = new JList(b.toArray());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Writing is working properly. The problem is the reading... it does not read any object (projet) What could be the problem?
As mentioned by EJP in comment and this SO post . if you are planning to write multiple objects in a single file you should write custom ObjectOutputStream , because the while writing second or nth object header information the file will get corrupt.
As suggested by EJP write as ArrayList , since ArrayList is already Serializable you should not have issue. as
out.writeObject(file) and read it back as ArrayList b = (ArrayList) in.readObject();
for some reason if you cant write it as ArrayList. create custome ObjectOutStream as
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
and change your writeObject as
try {
FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true);
MyObjectOutputStream out = new MyObjectOutputStream(fileOut );
for (projet a : file) {
out.writeObject(a);
}
out.close();
}
catch(Exception e)
{e.printStackTrace();
}
and change your readObject as
ObjectInputStream in = null;
try {
FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt");
in = new ObjectInputStream(fileIn );
while(true) {
try{
projet c = (projet) in.readObject();
b.add(c);
}catch(EOFException ex){
// end of file case
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}