Reputation: 1765
So I have a .csv file from excel and I want to read the data from it and use it.I have A main class called "Travel" that has hotels which are objects made from the class "Hotel".
The constructor of Hotel is the following:
Hotel(String name, String city, int stars, double cost, String imagePath);
The contents of the file is the following:
Hotel las Américas;Cartagena;4;150000;./data/imagenes/americas.jpg
Hilton Garden Inn;Orlando;4;260000;./data/imagenes/hilton.jpg
Royal Decameron Barú;Barú;4;878125;./data/imagenes/baru.jpg
Hilton Lima Miraflores;Lima;5;493843;./data/imagenes/lima.jpg
Soho Hotel;Barcelona;3;329053;./data/imagenes/barcelona.jpg
Hotel Darcet;París;2;260248;./data/imagenes/paris.jpg
Corales de Indias;Cartagena;4;294618;./data/imagenes/corales.jpg
Hampton Inn;Orlando;4;374300;./data/imagenes/hamptonInn.jpg
All-Star Movies Resort;Orlando;5;308111;./data/imagenes/disney.jpg
So the code I wrote in order to read this file is the following
try(BufferedReader bf = new BufferedReader(new FileReader(fileName))) {
while(bf.readLine( ) != null) {
String line = bf.readLine( );
System.out.println(line);
line.trim( );
String data[] = line.split(";");
Hotel hotel = new Hotel( data[0], data[1], Integer.parseInt( data[2] ), Double.parseDouble( data[3] ), data[4] );
hoteles.add( hotel );
}
} catch(Exception e) {
}
The problem is that I have an error when executing this because I got null reading a line, I had this variation to my code
try(BufferedReader bf = new BufferedReader(new FileReader(fileName))) {
while(bf.readLine( ) != null) {
if (bf.readLine()!= null) {
String line = bf.readLine( );
System.out.println(line);
line.trim( );
String data[] = line.split(";");
Hotel hotel = new Hotel( data[0], data[1], Integer.parseInt( data[2] ), Double.parseDouble( data[3] ), data[4] );
hoteles.add( hotel );
}
}
} catch(Exception e) {
}
Even do I guarantee that not null enters the code now, my code is just reading and saving the data for 3 hotels and not all of them.
If I add System.out.println(line); before line.trim() I have this output Hilton
Garden Inn;Orlando;4;260000;./data/imagenes/hilton.jpg
Hilton Lima Miraflores;Lima;5;493843;./data/imagenes/lima.jpg
Hotel Darcet;París;2;260248;./data/imagenes/paris.jpg
Hampton Inn;Orlando;4;374300;./data/imagenes/hamptonInn.jpg
null
that is still not all of them. What I am doing wrong?
Thanks
Upvotes: 0
Views: 88
Reputation: 151
Each call of bf.readLine() read next row. You must proccess all of them.
String line;
while ((line = bf.readLine()) != null) {
//split and proccess
}
Upvotes: 2