ファイルに保存するためにArrayListを取得しようとしています。私はそれがテキストファイルを作成しているのを見ることができますが、何もテキストファイルの中に置かれています、ただ空白です。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;
}
}
'saveToFile'のための' ArrayList'パラメータでジェネリックを使用すると、問題の原因となっている 'Files.write'に型エラーが現れます。 – 4castle
私は "動物"クラスを提供してください。私は解決策をお手伝いします。 – NulledCoder
@NulledCoder –