簡體   English   中英

用Java將對象數組寫入CSV文件

[英]Writing an object array to csv file in java

我正在嘗試獲取一個初始CSV文件,並將其通過檢查另一個文件(如果它具有A或D)的類傳遞,然后將其添加到數組對象或從中刪除。

pokemon.csv的示例:

1, Bulbasaur
2, Ivysaur
3, venasaur

changeList.csv的示例:

A, Charizard
A, Suirtle
D, 2

話雖這么說,將新數組的內容保存到新的CSV文件時遇到了很多麻煩。 我檢查了數組和類文件是否正常工作。 我一直在嘗試並且未能將“ pokedex1”對象數組的最終內容帶入新的CSV文件中。

主文件

import java.io.File; 
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class PokedexManager {

public static void  printArray(String[] array) {
    System.out.print("Contents of array: ");

    for(int i = 0; i < array.length; i++) {
        if(i == array.length - 1) {
            System.out.print(array[i]);
        }else {
            System.out.print(array[i] + ",");
        }
    }
    System.out.println();
}

public static void main(String[] args) {
    try {
        //output for pokedex1 using PokemonNoGaps class
        PokemonNoGaps pokedex1 = new PokemonNoGaps();

        //initializes scanner to read from csv file
        String pokedexFilename = "pokedex.csv";
        File pokedexFile = new File(pokedexFilename);
        Scanner pokescanner = new Scanner(pokedexFile);

        //reads csv file, parses it into an array, and then adds         new pokemon objects to Pokemon class
        while(pokescanner.hasNextLine()) {
            String pokeLine = pokescanner.nextLine();
            String[] pokemonStringArray = pokeLine.split(", ");
            int id = Integer.parseInt(pokemonStringArray[0]);
            String name = pokemonStringArray[1];
            Pokemon apokemon = new Pokemon(id, name);
            pokedex1.add(apokemon);
        }

        //opens changeList.csv file to add or delete entries from         Pokemon class
        String changeListfilename = "changeList.csv";
        File changeListFile = new File(changeListfilename);
        Scanner changeScanner = new Scanner(changeListFile);

        //loads text from csv file to be parsed to PokemonNoGaps class
        while(changeScanner.hasNextLine()) {
            String changeLine = changeScanner.nextLine();
            String[] changeStringArray = changeLine.split(", ");
            String action = changeStringArray[0];
            String nameOrId = changeStringArray[1];

            //if changList.csv file line has an "A" in the first spot add this entry to somePokemon
            if(action.equals("A")) {
                int newId = pokedex1.getNewId();
                String name = nameOrId;
                Pokemon somePokemon = new Pokemon(newId, name);
                pokedex1.add(somePokemon);
            }
            //if it has a "D" then send it to PokemonNoGaps class to delete the entry from the array
            else { //"D"
                int someId = Integer.parseInt(nameOrId);
                pokedex1.deleteById(someId);
            }
            //tests the action being taken and the update to the array
            //System.out.println(action + "\t" + nameOrId + "\n");
            System.out.println(pokedex1);

            //*(supposedly)* prints the resulting contents of the array to a new csv file
            String[] pokemonList = changeStringArray;
            try {
                String outputFile1 = "pokedex1.csv";
                FileWriter writer1 = new FileWriter(outputFile1);
                writer1.write(String.valueOf(pokemonList));
            } catch (IOException e) {
                System.out.println("\nError writing to Pokedex1.csv!");
                e.printStackTrace();
            }
        }
        //tests final contents of array after being passed through PokemonNoGaps class
        //System.out.println(pokedex1);

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

}

PokemonNoGaps類文件:

public class PokemonNoGaps implements ChangePokedex {
    private Pokemon[] pokedex = new Pokemon[1];
    private int numElements = 0;
    private static int id = 0;
    // add, delete, search

    @Override
    public void add(Pokemon apokemon) {
        // if you have space
        this.pokedex[this.numElements] = apokemon;
        this.numElements++;
        // if you don't have space
        if(this.numElements == pokedex.length) {
            Pokemon[] newPokedex = new Pokemon[ this.numElements * 2]; // create new array
            for(int i = 0; i < pokedex.length; i++) { // transfer all     elements from array into bigger array
                newPokedex[i] = pokedex[i];
            }
            this.pokedex = newPokedex;
        }
        this.id++;
    }

    public int getNewId() {
        return this.id + 1;
    }
    @Override
    public void deleteById(int id) {
        for(int i = 0; i < numElements; i++) {
            if(pokedex[i].getId() == id) {
                for(int j = i+1; j < pokedex.length; j++) {
                    pokedex[j-1] = pokedex[j];
                }
                numElements--;
                pokedex[numElements] = null;
            }
        }
    }

    public Pokemon getFirstElement() {
        return pokedex[0];
    }
    public int getNumElements() {
        return numElements;
    }
    public String toString() {
        String result = "";
        for(int i = 0; i < this.numElements; i++) {
            result += this.pokedex[i].toString() + "\n";
        }
        return result;
    }
}

超出的輸出:

1, Bulbasaur
3, Venasaur
4, Charizard
5, Squirtle

我使用了錯誤的文件編寫器嗎? 我是在錯誤的時間還是錯誤地致電文件編寫器? 換句話說,我不知道為什么我的輸出文件為空並且沒有加載數組內容。 有人可以幫我嗎?

String outputFile1 = "pokedex1.csv";
FileWriter writer1 = new FileWriter(outputFile1);

似乎在您的while循環內while因此每次都會創建一個新文件。

使用FileWriter(File file, boolean append)構造函數或在循環之前創建

運行此程序時,我發現了一些問題。 如上一個答案中所述,您希望在寫入新pokedx1.csv的代碼部分中將文件追加設置為true。

   try {
        String outputFile1 = "pokedex1.csv";
        FileWriter fileWriter = new FileWriter(prefix+outputFile1, true);
        BufferedWriter bw = new BufferedWriter(fileWriter);
        for(String pokemon : pokedex1.toString().split("\n")) {
            System.out.println(pokemon);
            bw.write(pokemon);
        }
        bw.flush();
        bw.close();
   } catch (IOException e) {
        System.out.println("\nError writing to Pokedex1.csv!");
        e.printStackTrace();
   }

我選擇使用緩沖讀取器作為解決方案。 我發現的另一個問題是您正在閱讀pokedex.csv,但文件名為pokemon.csv。

String pokedexFilename = "pokemon.csv";

我進行了上述更改以解決此問題。

在旁注中,我注意到您創建了多個掃描儀來讀取兩個文件。 對於這些類型的資源,優良作法是在使用完這些資源后立即調用close方法。 如下所示。

Scanner pokescanner = new Scanner(pokedexFile);
// Use scanner code here
// Once finished with scanner
pokescanner.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM