【问题标题】:How to read and write Object Arrays in JAVA ? I am facing Problems [closed]如何在 JAVA 中读写对象数组?我面临问题[关闭]
【发布时间】:2017-03-21 17:35:07
【问题描述】:

我有 10 个课程,我已经像这样链接它们 类 Person 链接在类 Array 中,我在 Array 类中获取了一个对象数组,就像这样

Person [] p = new Person[99];

public void generate(){

  for(int i=0;i<=p.length-1;i++)
  {
     p[i]=new Person();//this will allocate space for Persons
  }
}

现在我如何编写其他类存储的每个索引的数据? 以及终止后如何阅读。? 确实感谢

【问题讨论】:

    标签: java arrays object io


    【解决方案1】:

    要访问数组的元素,您可以简单地使用元素的索引:

    Person perfonFromIndex = p[index];
    

    如果你想在同一个数组中存储不同类型的对象,你可以声明这个类型的数组,你的所有类都从该数组派生,例如 Object 类: 对象[] p = 新对象[99];

    public void generate(){
      for(int i=0;i<p.length;i++)
      {
         p[i]=new Person();//this will allocate space for Persons
      }
    }
    

    但在这种情况下,你必须在每次想要获取特定类的元素时进行强制转换:

    SpecifiedClass perfonFromIndex = (SpecifiedClass)p[index];
    

    这是一个非常糟糕的解决方案。 更好的是通过使用多态来实现它:

    class Base{
        void method(){
            System.out.println("from Base");
        }
    }
    class Derived1 extends Base{
        @Override
        void method(){
            System.out.println("from Derived1");
        }
    }
    class Derived2 extends Base{
        @Override
        void method(){
            System.out.println("from Derived2");
        }
    }
    

    从现在开始,你不必每次都强制转换,你想调用指定时间的method(),java编译器就会知道应该调用哪个方法:

    Base[] arr = new Base[3];
    arr[0] = new Base();
    arr[1] = new Derived1();
    arr[2] = new Derived2();
    for(Base b : arr){
        b.method();
    }
    

    输出是:

    from Base
    from Derived1
    from Derived2
    

    有关多态性的更多信息,您可以阅读here

    【讨论】:

    • 谢谢我会做这个兄弟,但是!我已经存储了数据...现在我要做的就是...我想将存储的数据写入磁盘... import java.io.*;因为我不知道如何使用 io 。请您简要解释一下。
    • 这里是如何做这些事情的好教程:mkyong.com/java/…
    • 它适用于对象数组吗?
    • 是的,它会的。如果对您有帮助,请接受我的回答。
    • 当然,兄弟,谢谢 :)
    【解决方案2】:

    有多种方法可以将数据存储在磁盘上。一种通用方法是outputstream:

    /**
     *
     * @param object  - the object you want to store on disk
     * @param path    - the path where to store it (e.g: "c:\MyFiles\")
     * @param fileName - any name you like (e.g: "myArray.me")
     */   
    public static void saveFile(Object object, String path, String fileName){
        FileOutputStream fileOutPutStream = null;  // this stream will write the data to disk
        try{
            File newPath;   // a File object can be a file or directory in Java
            newPath = new File(path);  // this File object will represent the parent folder where you store your data
            newPath.mkdirs();  // let's create the directory first (in case it doesn't exist yet)
    
            fileOutPutStream = new FileOutputStream(new File(path, fileName));  // this will open the output stream to a file in your directory
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutPutStream)){  // try-with-resources will make sure your object output stream closes in the end (even on exceptions)
                objectOutputStream.writeObject(object); // this will actually write the object to the object outputstream
            }
        }catch(FileNotFoundException ex){   // shouldn't happen when you created your directories earlier
            logger.log(Level.WARNING, "Couldn''t save file {0} due to {1}", new Object[]{fileName, ex.toString()});
        }catch(IOException ex){   // thrown on any other input output problem 
            logger.log(Level.WARNING, "Couldn''t save file {0} due to {1}", new Object[]{fileName, ex.toString()});
        }finally{  // in any case, always close the file output stream afterwards
            try{
                fileOutPutStream.close();  // closes even when an exception was thrown
            }catch(IOException | NullPointerException ex){  // when closing, other errors can happen
                logger.log(Level.WARNING, "Couldn''t close file {0} due to {1}", new Object[]{fileName, ex.toString()});
            }
        }
    }
    

    您现在可以像这样使用此方法:

    Integer[] myNumbers = ...;
    saveFile(myNumbers, "arrays", "number.array");
    

    它将数组myNumbers 存储在您的程序名为“arrays”的子目录中,并将文件命名为“number.array”。您当然也可以使用绝对路径:“c:\myFiles\arrays”或“..\arrays”等相对路径“向上”移动一个目录。

    这就是您可以再次加载文件的方式:

     /**
     *
     * @param <T>  the type of your object that will be returned (e.g. int[])
     * @param path - as above, the directory where you stored the file
     * @param fileName  - the name of the file
     * @param objectType - the type of your object (e.g: int[].class)
     *
     */
     public static <T> T loadFile(String path, String fileName, Class<T> objectType){
        FileInputStream fileInputStream = null;  // instead of file output stream, an input stream
        T object = null;   // it's generic, so we don't know what type the return object will have - that's why we call it T
        try{
            fileInputStream = new FileInputStream(new File(path, fileName)); // will open the file input stream for us
            try(ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)){  // again, try-with-resources to get an Object input stream from the file input stream
                object = (T) objectInputStream.readObject();  // reads the object and casts it to T 
            }catch(IOException ex){
                logger.log(Level.WARNING, "Couldn''t load file {0} due to {1}", new Object[]{fileName, ex.toString()});
            }
            return object;  // returns the freshly read object
        }catch(FileNotFoundException ex){
            logger.log(Level.WARNING, "Couldn''t load file {0} due to {1}", new Object[]{fileName, ex.toString()});
        }finally{
            if(fileInputStream != null){
                try{
                    fileInputStream.close();
                }catch(IOException ex){
                    logger.log(Level.WARNING, "Couldn''t close file {0} due to {1}", new Object[]{fileName, ex.toString()});
                }
            }
            return object;  // might be null in case there was an error
        }
    }
    

    完整示例用法:

    public static void main(String[] args){
        int[] array = new int[2];
        array[0] = 1;
        array[1] = 2;
        saveFile(array, "arrays", "number.array");
    
        int[] array2 = loadFile("arrays", "number.array", int[].class);
        for(int i = 0; i < array2.length; i++){
            System.out.println("" + array2[i]);
        }
    }
    

    【讨论】:

    • 适用于对象数组?
    • 一个数组本身已经是一个对象(..sort of)请参阅我的更新。
    • 我添加了一个加载方法和一个更好的例子来说明如何使用它们
    • 好的,非常感谢!
    猜你喜欢
    • 2021-07-19
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2022-01-18
    相关资源
    最近更新 更多