Good morning everyone.
I'm not asking what is a NullPointerException. I'm asking if somebody knows, in the specific case of OpenCSV if it's possible to create two readers at the same time.
I'm trying to make a program that compares two columns on different CSV files.
So, what I do is open two readers, (Category and products), and then compare them and do some stuff.
So, the program sum up is: Initialices everything, creating the objects. Then I have two loops (I need to compare every product with all the categories). The first loop works perfectly, it's already tested. But when the program tries to start reading the second file it returns a NullPointerException.
The library I'm using is OpenCSV. They updated the 4.0v and I don't know if it's possible to have two readers opened at the same time. Or maybe I'm missing something.
Here's the code:
public class Traductor_CSV {
///////////////////////////////////////////////////////// VARIABLES /////////////////////////////////////////////////////
private final char SEPARADOR = ';';
private final char COMILLAS = '"';
private String[] nombres;
File CSVCat;
File CSVProd;
////////////////////////////////////////////////////// CONSTRUCTOR & START ///////////////////////////////////////////////////////
Traductor_CSV(String Path1, String Path2) {
CSVCat = new File(Path1);
CSVProd = new File(Path2);
}
/**
* Estaría bien que recibiese por parámetro también los números de las columnas a comparar. Además, este programa se puede
* ampliar con una base de datos para conseguir que se haga solo también el traductor y no el comparador.
*/
public void start () {
//Do Stuff º
LeerCSV(CSVCat, CSVProd);
}
///////////////////////////////////////////// MÉTODOS //////////////////////////////////////////////////////////////
/**
* Este método lee los CSV que se le pasan por parámetro. Además, guarda dentro del array de Strings
* "nombres" los nombres de las categorías que van llegando.
* @param CSVCat
* @param CSVProd
*/
public void LeerCSV(File CSVCat, File CSVProd){
//Creo un objeto de la clase FileReader que me hace falta para los CSVReader
CSVReader CatReader = null;
CSVReader ProdReader = null;
CSVParser CatParser;
CSVParser ProdParser;
String ruta = "C:\\Users\\ADMINISTRACION2\\Desktop\\Dropshipping\\Feeds de datos\\BigBuy CSV\\Productos_copia.csv";
File CSV_copia = new File(ruta);
//Vamos a intentar abrirlos y operar con ellos
try {
//Se crea una especie de "constructor" para crear los lectores de archivos.
//para ello, antes se le pasan todos los atributos que queramos
CatParser =
new CSVParserBuilder()
.withSeparator(SEPARADOR)
.withIgnoreQuotations(true)
.build();
CatReader =
new CSVReaderBuilder(new FileReader(CSVCat))
.withSkipLines(1)
.withCSVParser(CatParser)
.build();
ProdParser =
new CSVParserBuilder()
.withSeparator(SEPARADOR)
.withIgnoreQuotations(true)
.build();
ProdReader =
new CSVReaderBuilder(new FileReader(CSVProd))
.withSkipLines(1)
.withCSVParser(ProdParser)
.build();
//Definimos el array de Strings de la línea leída
String [] lineaCat;
String [] lineaProd = null;
int i=0;
try{
//Lee las líneas del CSV de PRODUCTOS primero y las pone en lineaProd []
while ((lineaProd = ProdReader.readNext())!= null){
//Creo un array de strings para guardar las categorías separadas por comas
// después, meto cada una en uno de los huecos del array y los imprimo. Hasta aquí todo ok.
// 17/08/2017
String [] categorias_split = null;
categorias_split = lineaProd[3].split(",");
// for (int j=0; j<categorias_split.length; j++){
//
// System.out.println(categorias_split[j] + " "); }
//
// System.out.println(lineaProd[3].toString() + "\n");
//Lee las líneas del CSV de CATEGORIAS cada vez que se lee una nueva de PRODUCTOS y lo pone en lineaCat[]
while ((lineaCat = CatReader.readNext())!= null) {
//Cada vez que lee una nueva línea, meto el nombre en su sitio
nombres [i] = lineaCat[2];
i++;
System.out.println (lineaCat[1]);
//Comparo cada columna con su correspondiente
// if(CompararColumnas (categorias_split, lineaCat[0])) {
// //Si son iguales, se copia
//
//
// copiarEnArchivo(CSV_copia ,nombres, lineaCat[0]);
// }
}
//Cierro el lector y creo otro para que me vuelva a entrar en el bucle en cada iteración.
CatReader.close();
CatReader =
new CSVReaderBuilder(new FileReader(CSVCat))
.withSkipLines(1)
.withCSVParser(CatParser)
.build();
}
} catch (IOException ex) {
Logger.getLogger(Traductor_CSV.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Traductor_CSV.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
try {
//En cualquier caso, lo cerramos al final.
CatReader.close();
ProdReader.close();
} catch (IOException ex) {
Logger.getLogger(Traductor_CSV.class.getName()).log(Level.SEVERE, null, ex);
}
}
The NullPointerException is this one:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at traductor_bigb.Traductor_CSV.LeerCSV(Traductor_CSV.java:144)
at traductor_bigb.Traductor_CSV.start(Traductor_CSV.java:57)
I hope it helps. Thanks everyone.