将ArrayList保存到文本文件

时间:2016-06-27 03:06:15

标签: java arraylist io

我一直在尝试将ArrayList保存到文件中。我可以看到它正在创建文本文件,但文本文件中没有任何内容,只是空白。

这是带有ArrayList的主代码,Switch带有保存选项。

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;
}

}

3 个答案:

答案 0 :(得分:3)

有两处变化:

  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 + "]";
            }
    
    
            }
    

答案 1 :(得分:2)

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

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(); } }

试试吧。 Theres也可能是一些错误/错误拼写,因为我从手机上写了这段代码。

答案 2 :(得分:1)

您只能编写allops = tf.group(myscope_0/result, myscope_1/result) ,因此请更改以下代码。

请务必覆盖Iterable<? extends CharSequence>

toString方法
Animal