Java中的FileNotFound异常 [英] FileNotFound Exception in Java

查看:160
本文介绍了Java中的FileNotFound异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我是Java的新手)...我想在HashMap中存储一些类字段值,然后将其写入文件(路径作为参数传递),然后还原HashMap并获取所需的信息.在名为Carte的构造函数中,我遇到一个异常,即找不到文件,无论如何它都位于正确的位置,保存的数据位于我的xml文件中.关于这一点的任何想法

(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

发生了一个异常:java.io.FileNotFoundException:users/stefan/desktop/lol.xml(没有这样的文件或目录)

// 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

}

推荐答案

查看消息:

发生了异常:java.io.FileNotFoundException:users/stefan/desktop/lol.xml

An exception has occured : java.io.FileNotFoundException: users/stefan/desktop/lol.xml

请注意,它是"users/stefan/[...]"-它是一个相对文件名,因此将相对于当前工作目录进行解析.您确定您不是要在"/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?

这篇关于Java中的FileNotFound异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆