【发布时间】:2016-10-28 22:58:34
【问题描述】:
我一直在尝试将 ArrayList 保存到文件中。我可以看到它正在创建文本文件,但文本文件中没有任何内容,只是空白。
这里是 ArrayList 的主要代码,带有保存选项的开关。
static int input, selection, i = 1;
static ArrayList<Animals> a;
// Main Method
public static void main(String[] args){
// Create an ArrayList that holds different animals
a = new ArrayList<>();
a.add(new Animals(i++, "Bear", "Vertebrate", "Mammal"));
a.add(new Animals(i++, "Snake", "Invertebrate", "Reptile"));
a.add(new Animals(i++, "Dog", "Vertebrate", "Mammal"));
a.add(new Animals(i++, "Starfish", "Invertebrates", "Fish"));
while (true) {
try {
System.out.println("\nWhat would you like to do?");
System.out.println("1: View List\n2: Delete Item\n3: Add Item\n4: Edit Item\n5: Save File\n0: Exit");
selection = scanner.nextInt();
if(selection != 0){
switch (selection) {
case 1:
ViewList.view();
Thread.sleep(4000);
break;
case 2:
Delete.deleteItem();
Thread.sleep(4000);
break;
case 3:
Add.addItem();
Thread.sleep(4000);
break;
case 4:
Edit.editItem();
Thread.sleep(4000);
break;
case 5:
Save.saveToFile("animals.txt", a);
Thread.sleep(4000);
break;
这是我为处理文件而写的。
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Save extends ALProgram{
public static void saveToFile(String fileName, ArrayList list){
Path filePath = Paths.get(fileName);
try{
System.out.println("File Saved");
Files.write(filePath, list, Charset.defaultCharset());
}catch(IOException e){
e.printStackTrace();
}
}
}
这里是动物课
class Animals {
public int id;
public String type, vertebrate, aclass;
public Animals(int id, String type, String vertebrate, String aclass) {
this.id = id;
this.type = type;
this.vertebrate = vertebrate;
this.aclass = aclass;
}
public int getID() {
return id;
}
public String getType() {
return type;
}
public String getVert() {
return vertebrate;
}
public String getaclass() {
return aclass;
}
}
【问题讨论】:
-
如果你在参数
ArrayList上为saveToFile使用泛型,它会在Files.write上显示导致问题的类型错误。 -
请给我提供“动物”类,我会帮你解决的。
-
@NulledCoder 我添加了要编辑的类
-
@4castle 是我正在寻找的错误:“文件类型中的方法 write(Path, Iterable extends CharSequence>, Charset, OpenOption...) 不适用于参数(路径,ArrayList
, Charset)" -
是的,这是正确的错误。问题是它意味着传递一个扩展
CharSequence的对象List。您可能应该遍历列表并创建另一个列表,其中填充代表每个Animal的字符串值。