问题
(i'm new in Java) ... I want to store some class fields values in a HashMap then write it to a file (the path is passed as an argument) and then restore HashMap and fetch needed info. In my constructor called Carte, i get an exception that file is not found , anyway it's in the right place and saved data is in my xml file. Any ideas on this point
An exception has occured : java.io.FileNotFoundException: users/stefan/desktop/lol.xml (No such file or directory)
// Salveaza toate obiectele create intr-un fisier
public void salveazaObiecteleCreate(String caleSpreFisier) {
HashMap table = new HashMap();
table.put("Autorul", numelePrenumeleAutorului);
table.put("Denumirea cartii", denumireaCartii);
table.put ("Culoarea cartii",culoareaCartii);
table.put ("Genul cartii ",gen);
table.put ("Limba",limba);
table.put ("Numarul de copii",numarulDeCopii);
table.put ("Numarul de pagini",numarulDePagini);
table.put ("Pretul cartii",pretulCartii);
try {
File file = new File(caleSpreFisier);
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(table);
s.close();
} catch(Exception e){
System.out.println("An exception has occured");
}
}
public Carte (String caleSpreFisier) {
HashMap table = new HashMap();
File file = new File(caleSpreFisier);
try {
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
table = (HashMap)s.readObject();
s.close();
} catch(Exception e){
System.out.println("An exception has occured : "+e);
}
for (Object key: table.keySet()) {
System.out.println(table.get(key));
}
}
// end of class
}
回答1:
Look at the message:
An exception has occured : java.io.FileNotFoundException: users/stefan/desktop/lol.xml
Note that it's "users/stefan/[...]" - it's a relative filename, so will be resolved relative to the current working directory. Are you sure you didn't mean "/users/stefan/desktop/lol.xml" with a leading slash to indicate an absolute filename?
来源:https://stackoverflow.com/questions/7576065/filenotfound-exception-in-java