プログラムに特定の配列リストがあり、それをファイルに書き込みたいので、プログラムを 2 回目に開始するときにそれらを読み取ることができます。現在、人の配列リストに対して機能します。
読書の部分:
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("test.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
team.setPersonList((ArrayList<Person>) ois.readObject());
writeToFile クラス:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class WriteToFile {
public void write(ArrayList<Person> Data ) throws IOException, ClassNotFoundException{
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(Data);
// close the stream
oout.close();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("test.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// read and print what we wrote before
System.out.println("" + ois.readObject());
ois.close();
}
}
主に:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IOException{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
Team team = new Team(scan);
new InlogSystem(team, scan);
ArrayList<Person> playersData = team.getPersonList();
WriteToFile x = new WriteToFile();
x.write(playersData);
scan.close();
}
}
これが作業部分です。同じ writeToFile クラスを使用して、文字列の配列リストを別の txt ファイル (personlist のようにテストしない) に書き込む必要があります。明らかに、writemethod はタイプ person の arraylist に対してのみ機能し、常に配列を「test.txt」に保存します。
新しいメソッドを作成したり、あいまいなコードを大量に使用したりせずに、この配列リストを作成するにはどうすればよいですか? どうもありがとう!