且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何保存和载入Java中的数组

更新时间:2023-02-02 21:13:33

虽然你可以序列化对象,并将其写入到磁盘...我猜测它会更容易让你简单地输出阵列到文件和读取回。你可以很容易地编写数组在一个循环文件​​中的每一个元素,并很容易地读取它。而像其他人说,这是值得你花时间寻找到一个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());
}