0

我正在尝试读取文件并通过下面的代码对其进行序列化。但是,我不断收到未找到文件的错误。我尝试将文件放在桌面上的文件夹中并在 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");
        }
    }
}
4

1 回答 1

-1

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

还要检查您是否有权访问该文件。尝试将文件移动到C:\并查看它是否可读。

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

File f = new File(filePathString);
if(f.exists()) { /* do something */ }
于 2013-09-29T04:34:49.753 回答