jeudi 30 juin 2016

Saving ArrayList to Text File

I have been trying to get an ArrayList to save to a file. I can see it is creating the text file, but nothing is placed inside the text file, just blank.

Here is the main code with the ArrayList,Switch with option to save.

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 Listn2: Delete Itemn3: Add Itemn4: Edit Itemn5: Save Filen0: 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;

This is what I have written to handle file.

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

     }
}

Here is Animal Class

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

}

Aucun commentaire:

Enregistrer un commentaire