简体   繁体   English

用Java将对象数组写入CSV文件

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

I am trying to take an initial CSV file, pass it through a class that checks another file if it has an A or a D to then adds or deletes the associative entry to an array object. 我正在尝试获取一个初始CSV文件,并将其通过检查另一个文件(如果它具有A或D)的类传递,然后将其添加到数组对象或从中删除。

example of pokemon.csv: pokemon.csv的示例:

1, Bulbasaur
2, Ivysaur
3, venasaur

example of changeList.csv: changeList.csv的示例:

A, Charizard
A, Suirtle
D, 2

That being said, I am having a lot of trouble getting the content of my new array to a new CSV file. 话虽这么说,将新数组的内容保存到新的CSV文件时遇到了很多麻烦。 I have checked to see whether or not my array and class files are working properly. 我检查了数组和类文件是否正常工作。 I have been trying and failing to take the final contents of "pokedex1" object array into the new CSV file. 我一直在尝试并且未能将“ pokedex1”对象数组的最终内容带入新的CSV文件中。

Main File 主文件

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 class file: 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;
    }
}

Excpeted output: 超出的输出:

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

Am i using the wrong file writer? 我使用了错误的文件编写器吗? Am I calling the file writer at the wrong time or incorrectly? 我是在错误的时间还是错误地致电文件编写器? In other words, I do not know why my output file is empty and not being loaded with the contents of my array. 换句话说,我不知道为什么我的输出文件为空并且没有加载数组内容。 Can anybody help me out? 有人可以帮我吗?

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

appears to be within your while loop so a new file will be created every time. 似乎在您的while循环内while因此每次都会创建一个新文件。

Either use the FileWriter(File file, boolean append) constructor or create before the loop 使用FileWriter(File file, boolean append)构造函数或在循环之前创建

I spotted a few issues whilst running this. 运行此程序时,我发现了一些问题。 As mentioned in previous answer you want to set file append to true in the section of code that writes to the new pokedx1.csv 如上一个答案中所述,您希望在写入新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();
   }

I opted to use buffered reader for the solution. 我选择使用缓冲读取器作为解决方案。 Another issue I found is that your reading pokedex.csv but the file is named pokemon.csv. 我发现的另一个问题是您正在阅读pokedex.csv,但文件名为pokemon.csv。

String pokedexFilename = "pokemon.csv";

I made the above change to fix this issue. 我进行了上述更改以解决此问题。

On a side note I noticed that you create several scanners to read the two files. 在旁注中,我注意到您创建了多个扫描仪来读取两个文件。 With these types of resources its good practice to call the close method once you have finished using them; 对于这些类型的资源,优良作法是在使用完这些资源后立即调用close方法。 as shown below. 如下所示。

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