如何保存和载入Java中的数组 [英] How to save and load a Array in Java

查看:220
本文介绍了如何保存和载入Java中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建一个计划,将跟踪的电视节目和电影,我看的。我有2类(电视和电影),我有持有人人数组。我怎么会去拯救这个数组,这样每次我用它让我编辑同一个列表中的程序时间,因为我每次看新的一集我想更新我的数组使用新的信息。所以基本上什么程序我需要为了使用,不仅保存arrya但我每次运行程序时加载的阵列?

So I am creating a program which will keep track of the TV shows and Movies that I watch. I have 2 classes (TV and Movie) and I have an Array which holds everyone. How would i go about saving this array so that every time I use the program it lets me edit the same list, because every time I watch a new episode I want to update my array with the new information. So basically what procedure would I need to use in order to not only save an arrya but load up the array every time I run the program?

推荐答案

虽然你可以序列化对象,并将其写入到磁盘...我猜测它会更容易让你简单地输出阵列到文件和读取回。你可以很容易地编写数组在一个循环文件​​中的每一个元素,并很容易地读取它。而像其他人说,这是值得你花时间寻找到一个ArrayList或类似结构!例如:

While you could serialize your object and write it to disk... I am guessing it would be easier for you to simply output your array to a file and read it back in. You can write each element in the array to the file in a loop fairly easily, and read it back in just as easily. And like the others said, it is worth your time to look into an ArrayList or similar structure! Example:

要写入文件:

ArrayList<String> list = new ArrayList<String>();

// add stuff the the ArrayList

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("data.txt")));

for( int x = 0; x < list.size(); x++)
{
out.println(list.get(x));
}

out.close()

要从文件中读取:

ArrayList<String> list = new ArrayList<String>();

Scanner scan = new Scanner(new File("data.txt"));

while(scan.hasNext())
{
list.add(scan.next());
}

这篇关于如何保存和载入Java中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆