【问题标题】:Saving ArrayList to Text File将 ArrayList 保存到文本文件
【发布时间】: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 的字符串值。

标签: java arraylist io


【解决方案1】:

有两个变化:

  1. 您的类需要实现 CharSequence 才有资格传递给 Files.write。
  2. 您需要重写 toString 方法来指定保存时内容的外观。 我可以看到以上两个更改后的输出。

        class Animals implements CharSequence {
    
            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;
            }
    
            @Override
            public int length() {
                return toString().length();
            }
    
            @Override
            public char charAt(int index) {
                return toString().charAt(index);
            }
    
            @Override
            public CharSequence subSequence(int start, int end) {
                return toString().subSequence(start, end);
            }
    
            /* (non-Javadoc)
             * @see java.lang.Object#toString()
             */
            @Override
            public String toString() {
                return "Animals [id=" + id + ", type=" + type + ", vertebrate=" + vertebrate + ", aclass=" + aclass + "]";
            }
    
    
            }
    

【讨论】:

  • 效果很好,我对自己做错了什么看得更清楚了。谢谢!
【解决方案2】:

所以,第一个,你不能通过将它转换为字符串来保存它。 您需要获取每个元素,构建一个字符串,然后将其写入文件。 这是一个例子:

public static void saveToFile(String fileName, ArrayList<Animal> list){

StringBuilder sb = new StringBuilder();

for(int i=0; i<=list.size(); i++) {
Animal lAn = list.get(i);
sb.Append("Animal ID: "+lAn.getID()+"; Animal type: "+lAn.getType()+"; Animal vert: "+lAn.getVert()+"; Animal aclass: "+lAn.getaclass()+"\r\n");
}

try (PrintStream out = new PrintStream(new FileOutputStream(fileName))) { out.print(sb.toString()); }

} catch(IOException e){ e.printStackTrace(); } }

试试看。也可能存在一些错误/拼写错误,因为我是用手机编写的。

【讨论】:

    【解决方案3】:

    你只能写Iterable&lt;? extends CharSequence&gt;,所以像下面这样改变你的代码。

    请确保覆盖Animal类的toString方法

        List<Animal> animals = new ArrayList<>();
        Animal a1 = new Animal(1L, "XYZ", "A2B");
        Animal a2 = new Animal(2L, "ABC", "IJK");
        animals.add(a1);
        animals.add(a2);
        List<String> strings = new ArrayList<>();
        for (Animal animal : animals) {
            strings.add(animal.toString());
        }
        Files.write(Paths.get("output.out"), strings, Charset.defaultCharset());
    

    【讨论】:

    • 您可以通过这种方式将哈希值打印到文件中。
    • 我已经覆盖了toString 忘了提及,谢​​谢,编辑答案
    猜你喜欢
    • 1970-01-01
    • 2015-04-30
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2014-05-11
    • 2017-03-25
    • 2021-12-13
    相关资源
    最近更新 更多