Сохранение коллекции в текстовый файл
Я пытался получить 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 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;
Это то, что я написал для обработки файла.
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 ответа:
Есть два изменения:
- Ваш класс должен реализовать CharSequence, чтобы иметь право быть переданным в файлы.писать.
Вам нужно переопределить метод 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 + "]"; } }
Итак, во-первых, вы не можете просто сохранить его, бросив его в строку. Вам нужно получить каждый элемент, построить строку 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(); } }
Попробуйте. Там также могут быть некоторые ошибки / неправильный перевод, потому что я написал этот код с моего телефона.
Вы можете написать только
Iterable<? extends CharSequence>
, поэтому измените код, как показано ниже.Пожалуйста, не забудьте переопределить
toString
МетодAnimal
класса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());