将列表写入文件 [英] Writing a list to a file

查看:24
本文介绍了将列表写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列表中的所有元素存储在一个文件中以供以后检索,以便在程序关闭时不会丢失该数据.这可能吗?我已经写了一些代码来尝试,但这不是我想要的.到目前为止,这就是我所写的.

I'm trying to store all elements in a List in a file for later retrieval so when the program closes that data isn't lost. Is this possible? I've written some code to try, but it's not what I want. This is what I have written so far though.

import java.util.*;
import java.io.*;
public class Launch {
    public static void main(String[] args) throws IOException {
        int[] anArray = {5, 16, 13, 1, 72};
        List<Integer> aList = new ArrayList();
        for (int i = 0; i < anArray.length; i++) {
            aList.add(anArray[i]);
        }
        File file = new File("./Storage.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < aList.size(); i++) {
            bw.write(aList.get(i));
        }
        bw.flush();
        bw.close();
    }
}

建议?

我正在寻找要写入文件的数组本身,但这就是写入的内容.

I'm looking for the array itself to be written in the file, but this is what is writing.

推荐答案

import java.util.*;
import java.io.*;
public class Launch {
    public static void main(String[] args) throws IOException {
        int[] anArray = {5, 16, 13, 1, 72};
        List<Integer> aList = new ArrayList();
        for (int i = 0; i < anArray.length; i++) {
            aList.add(anArray[i]);
        }
        File file = new File("./Storage.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < aList.size(); i++) {
            bw.write(aList.get(i).toString());
        }
        bw.flush();
        bw.close();
    }
}

我编辑了 bw.write 行,在写入之前将 int 更改为字符串.

I edited the bw.write line to change the int to a string before writing it.

这篇关于将列表写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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