【问题标题】:Serializing Custom Objects in Java - java.io.FileNotFoundException在 Java 中序列化自定义对象 - java.io.FileNotFoundException
【发布时间】:2022-01-11 03:27:34
【问题描述】:

我有一个方法要求我序列化自定义类“分数”的对象。当我尝试保存对象时,我得到一个 java.io.FileNotFoundException。我可以做些什么来帮助缓解这个问题?

    public static void method3()  
    {
        //Serialize the Fraction class.  Save all the objects to a file named 
        //     <your name>Fractions.dat
        //replace <your name> with your name in the file name!
        //Be sure to close() the file after writing the data.

        Fraction[] fa =
        {
            new Fraction(35, 18), new Fraction(125, -30), new Fraction(-125, -30),
            new Fraction(0, 76), new Fraction(98, 12)
        };

        ArrayList<Fraction> alf = new ArrayList<Fraction>();
        alf.add(new Fraction(81, 9));
        alf.add(new Fraction(-75, 250));
        alf.add(new Fraction(2380, 754));
        
        
        //save all objects to the file here
        
        String fileName = "<your name>Fractions.dat";

        try {  
            ObjectOutputStream serializer = new ObjectOutputStream(new FileOutputStream(fileName));
            serializer.writeObject(fa); 
            serializer.writeObject(alf);
            serializer.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            System.out.println("A problem occurred when serializing.");
            e.printStackTrace();
        }
       
    }

//I made sure to have the Fraction class implement Serializable as demonstrated below

import java.io.Serializable;

public class Fraction implements Comparable<Fraction>, Serializable
{
    

【问题讨论】:

  • "&lt;your name&gt;Fractions.dat" 在您看来是一个有效的文件名吗?
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: java serialization filenotfoundexception objectoutputstream custom-object


【解决方案1】:

您使用的文件名无效:

String fileName = "<your name>Fractions.dat";

这在基本上任何操作系统上都不是有效名称。很明显你应该替换&lt;your name&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多