如何在JAVA中读写对象数组?我正面临着问题

时间:2016-11-08 07:15:49

标签: java arrays object io

我有10个课程,我已经将它们联系起来了 class Person在类Array中链接,我已经在Array Class中获取了一个像这样的对象数组

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

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

2 个答案:

答案 0 :(得分:0)

要访问数组的元素,只需使用元素的索引:

Person perfonFromIndex = p[index];

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

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

但是在这种情况下,每次想要获得sepcified类的元素时都必须进行转换:

SpecifiedClass perfonFromIndex = (SpecifiedClass)p[index];

这是非常糟糕的溶解。 更好的方法是使用polymorphysm实现它:

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");
    }
}

从现在开始,你不必每次都要强制转换,你想调用指定时间的方法(),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

答案 1 :(得分:0)

有多种方法可以将数据存储在磁盘上。一个通用方法是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”来一个目录“up”。

这就是你可以再次加载文件的方法:

 /**
 *
 * @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]);
    }
}