【问题标题】:Create file of array list创建数组列表文件
【发布时间】:2014-01-01 08:06:09
【问题描述】:

如何在 Java 中创建文件? 如果我有按数组列表添加的数据 我想要保存文件,如果输入新的用户信息将保存在文件中。

我可以写吗?

ArrayList<Example> e= new ArrayList<Example>();
Scanner input = new Scanner(System.in) ;

FileWriter writ = new FileWriter ("Example.txt" ) 

writ.write("Hello \n" + e.add(new Example("jack","USA","12345"))); //if the date exist

writ.write("Hello \n" + e.add(new Example(input.nextLine(),input.nextLine(),input.nextLine()))); //if user inter data  

如果没有添加数据,那是什么错误?

【问题讨论】:

  • e.add 会返回 void,所以 Hello 之后什么都不会写。您需要打印要添加的示例对象。您将要覆盖示例类中的 toString() 以便它可以正确打印。
  • 1) 标题中无需添加主要标签。 2) 请在句首加一个大写字母。还要为单词 I 使用大写字母,以及 JEE 或 WAR 等缩写词和首字母缩略词。这使人们更容易理解和帮助。 3) 为了尽快获得更好的帮助,请发布SSCCE。 4) “我可以写吗?”当你尝试它时发生了什么?你的编译器/运行时可以比我们更快、更准确地提供答案。
  • 您的问题并不清楚为什么您使用 ArrayList。您是否需要存储“示例”并同时将其写入文件?或者干脆将它们全部添加到 ArrayList 中,然后将其保存到文件中?

标签: java file file-io arraylist


【解决方案1】:

举个例子,我会将所有元素添加到 ArrayList 中,然后打印出来,我相信这就是你想要实现的目标,对吧?

ArrayList<Example> e= new ArrayList<Example>();
e.add(new Example("jack","USA","12345"));
e.add(new Example("jones","USA","52365"));

FileWriter writ = new FileWriter ("Example.txt" );

for(Example item : e){
    writ.write("Hello \n" + item.toString()); // If you have overridden toString()
}

writ.close(); // Flush and close the file!

这是一个简单的例子...请记住在您的 Example 类上覆盖 toString(),否则您会看到类似 { Object... } printet 的内容。

【讨论】:

    【解决方案2】:

    你应该close()你的文件来保存数据。

    ArrayList<Example> e= new ArrayList<Example>();
    Scanner input = new Scanner(System.in); //Add semicolon
    FileWriter writ = new FileWriter ("Example.txt"); 
    writ.write("Hello \n" + e.add(new Example("jack","USA","12345")));
       // e.add will return true if add() is success
    ....
    writ.close(); //Close the file after write
    

    【讨论】:

    • 它写'true'的原因是,如果添加了对象,则ArrayList的add()方法返回true,否则返回false。因此,正如 Collection.add(E) 所指定的,它将返回 true,因为如果无法添加对象,您将收到异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多