【问题标题】:read an arrayList and store this in a File Java [closed]读取arrayList并将其存储在文件Java中[关闭]
【发布时间】:2015-02-24 08:17:33
【问题描述】:

我想读取一个数组列表并将这些字符串存储到一个文件中。 这是我的一些代码:

output = new Formatter(nameFile + ".txt");

 while (textLines.hasNext()){
        output.format(nameFile, textLines);
    }

【问题讨论】:

  • 什么是问题
  • 什么是按预期工作或没有按预期工作?
  • 有问题还是您只是在向我们展示您的作品。
  • 我有一个 ArrayList,在这个 arraylist 中有字符串。但我想把这些字符串放在一个文件中。我的代码不起作用,所以也许你有解决方案?

标签: java file arraylist


【解决方案1】:
public class test1 {

    public static void main(String args[]) throws IOException{

        StringBuffer sb = new StringBuffer();
        String filepath = "test.txt";
        List<String> list = new ArrayList<String>(); 
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");

        Iterator<String> it = list.iterator();
        while(it.hasNext())
        {
            sb.append(it.next());
            sb.append(",");
        }

        BufferedWriter bw = new BufferedWriter(new FileWriter(filepath));
        bw.write(sb.toString());
        bw.flush();
        bw.close();
    }
}

【讨论】:

    【解决方案2】:

    试试这个

     PrintWriter writer = new PrintWriter("file-name.txt");
     for(String s:yourList)    //iterate your ArrayList here
     {
        writer.println(s);
     }
     writer.close();
    

    【讨论】:

    • @user3649644 如果对您有用,请选择答案
    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多