我正在写一个Java程序,显示一系列课外俱乐部(例如,足球,曲棍球-由用户输入)。这些俱乐部将被添加到以下ArrayList
中
private ArrayList<Club> clubs = new ArrayList<Club>();
通过以下方法:
public void addClub(String clubName) {
Club club = findClub(clubName);
if (club == null)
clubs.add(new Club(clubName));
}
‘'Club’是一个带有构造函数名的类:
public class Club {
private String name;
public Club(String name) {
this.name = name;
}
//There are more methods in my program but don't affect my query..
}
我的程序运行正常--它允许我添加一个新的Club对象到我的arraylist中,我可以查看arraylist,我可以删除任何我想要的等等。
但是,我现在希望将arrayList (俱乐部)保存到一个文件中,然后我希望稍后能够加载该文件,并且相同的数组列表再次出现。
我有两个方法(见下文),并一直试图让它工作,但没有任何运气,任何帮助或建议将不胜感激。
保存方式(fileName由用户选择)
public void save(String fileName) throws FileNotFoundException {
String tmp = clubs.toString();
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
pw.write(tmp);
pw.close();
}
Load方法(当前代码不会运行- File是一个字符串,但需要是Club?
public void load(String fileName) throws FileNotFoundException {
FileInputStream fileIn = new FileInputStream(fileName);
Scanner scan = new Scanner(fileIn);
String loadedClubs = scan.next();
clubs.add(loadedClubs);
}
我还使用GUI来运行该应用程序,此时,我可以单击我的Save按钮,然后我可以输入名称和位置并保存它。文件将出现,并可在记事本中打开,但显示为类似Club@c5d8jdj的内容(适用于我列表中的每个俱乐部)
发布于 2016-05-04 00:01:42
在Java8中,您可以使用带有两个参数的Files.write()方法:Path
和List<String>
,如下所示:
List<String> clubNames = clubs.stream()
.map(Club::getName)
.collect(Collectors.toList())
try {
Files.write(Paths.get(fileName), clubNames);
} catch (IOException e) {
log.error("Unable to write out names", e);
}
发布于 2013-04-20 03:04:28
这可能对你有用
public void save(String fileName) throws FileNotFoundException {
FileOutputStream fout= new FileOutputStream (fileName);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(clubs);
fout.close();
}
要回读,您可以使用
public void read(String fileName) throws FileNotFoundException {
FileInputStream fin= new FileInputStream (fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
clubs= (ArrayList<Clubs>)ois.readObject();
fin.close();
}
发布于 2013-04-20 02:55:50
ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();
此外,您的“添加”逻辑在逻辑上等同于使用集合而不是列表。列表可以有重复项,集合不能有重复项。您应该考虑使用set。毕竟,你真的可以在同一所学校里有两个国际象棋俱乐部吗?
https://stackoverflow.com/questions/16111496
复制相似问题