Запись массива объектов в CSV-файл в Java - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь взять исходный 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

Использую ли я неправильный файловый модуль записи?Я звоню в файл писателя в неправильное время или неправильно?Другими словами, я не знаю, почему мой выходной файл пуст и не загружается с содержимым моего массива.Кто-нибудь может мне помочь?

Ответы [ 2 ]

0 голосов
/ 26 сентября 2018

Я обнаружил несколько проблем во время работы.Как упоминалось в предыдущем ответе, вы хотите установить для файла append значение true в разделе кода, который записывает данные в новый pokedx1.csv

   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();
0 голосов
/ 26 сентября 2018
String outputFile1 = "pokedex1.csv";
FileWriter writer1 = new FileWriter(outputFile1);

, кажется, находится внутри вашего цикла while, поэтому каждый раз будет создаваться новый файл.

Либо используйте конструктор FileWriter(File file, boolean append), либо создайте перед циклом

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...