java.io.FileNotFoundException错误

时间:2013-09-29 04:26:52

标签: java file-io error-handling

我正在尝试读取文件并通过以下代码将其序列化。但是,我一直收到文件未找到错误。我已经尝试将文件放在桌面上的文件夹中,并在eclipse中创建一个新文件。请帮忙。

代码:

public class Util implements Serializable {

    public static void main (String[] args) throws FileNotFoundException {
        try {
            Automobile ford = new Automobile();
            FileReader fr = new FileReader(
                        "C:/Users/FName LName/Desktop/Data.txt");
            BufferedReader br = new BufferedReader (fr);
            String line = new String ();

            FileOutputStream fos = new FileOutputStream ("car.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);

            FileInputStream fis = new FileInputStream ("car.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);

            int k=0;
            while ((line = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line);
                String s = new String ();
                if (st.hasMoreTokens()) {
                    s = st.nextToken();
                }

                OptionSet list = new OptionSet ();
                int j = 0;
                while (st.hasMoreTokens()) {
                    String temp = st.nextToken();
                    String name = new String ();
                    int price = 0;
                    StringTokenizer token = new StringTokenizer (temp);
                    while (token.hasMoreTokens()) {
                        name = token.nextToken(",");
                        price = Integer.parseInt(token.nextToken(","));
                        list.setOption(j,name,price);   
                    }
                    j++;
                }
                list.setName(s);
                ford.getOs().add(k, list);
                k++;
            }
            oos.writeObject(ford); 
            ford = (Automobile) ois.readObject(); 

            for(int i=0;i< ford.getOs().size();i++) {
                System.out.print(ford.getOs().get(i).getName()+":");
                for(int j=0;j<ford.getOs().get(i).getOpt().size();j++) {
                    System.out.print(ford.getOs().get(i).getOpt().get(j).getName() +
                            "," + ford.getOs().get(i).getOpt().get(j).getCost()+" ");
                }
                System.out.println();
            }

            ois.close();
            oos.flush();
            oos.close();
            br.close();
        } catch (IOException e) {
            System.out.println("File not found");
        } catch (ClassNotFoundException e) {
            System.out.println("File not found");
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

您可以尝试重命名文件夹FName LName,使其没有空格吗?空间可能是一个问题。也可以使用反斜杠(使用其他\进行转义)来尝试:C:\\Users\\FName LName\\Desktop\\Data.txt

同时检查您是否拥有该文件的权限。尝试将文件移至C:\,看看它是否可读。

如果这些都不起作用,您可以尝试检查JVM是否可以看到该文件:

File f = new File(filePathString);
if(f.exists()) { /* do something */ }