简体   繁体   English

如何在读/写对象Java中列出或排列数组

[英]How to List or Array in Read/Write Object Java

*This is the main class, i want the output display 2 name likes *这是主类,我希望输出显示2个名称喜欢

  1. John ,ss,22 约翰·萨斯22
  2. Hon ,sxx,32 荣誉勋章32

So anyone know how to use array @ list in this code? 因此,有人知道如何在此代码中使用数组@ list吗?

private static final String filepath="C:\\Users\\im\\Desktop\\obj.txt";

public static void main(String args[]) {
    Soalan1 objectIO = new Soalan1();

    //List<List<String>> outter = new ArrayList<List<String>>(); 
    //List<String> inner2 = new ArrayList<String>();
    //List<int> Student = new List<int>();

    Student slist = new Student("John","ss",22);  <==== here i want change it to array/list

    objectIO.WriteObjectToFile(filepath, slist);

    //Read object from file
    Student st = (Student) objectIO.ReadObjectFromFile(filepath);
    System.out.println(st);
}

public void WriteObjectToFile(String filepath,Object serObj) {
    try {
        FileOutputStream fileOut = new FileOutputStream(filepath);
        ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
        objectOut.writeObject(serObj);
        objectOut.close();
        System.out.println("The Object  was succesfully written to a file");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public Object ReadObjectFromFile(String filepath) {
    try {
        FileInputStream fileIn = new FileInputStream(filepath);
        ObjectInputStream objectIn = new ObjectInputStream(fileIn);
        Object obj = objectIn.readObject();

        System.out.println("The Object has been read from the file");
        objectIn.close();
        return obj;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
Student slist[] = new Student[2];
slist[1] = new Student("John", "ss", 22);
slist[2] = new Student("Hon", "sxx", 32);

From this point it's just simple I/O and a loop: 从这一点来看,这只是简单的I / O和循环:

for (int i = 0; i<slist.length; i++)
  objectIO.WriteObjectToFile(filepath, slist[i]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM