0

I want to load data from a text file as required for part of a basic project. E.g. a text file can look like this:

201,double,70.00,2,own bathroom
202,single,50.00,2,own bathroom

Each piece of data is seperated by a comma, and in this case goes in the order: room number, room type, cost, amount of people, with/without bathroom and there's 5 data for each room and each room information is on a new line.

The code below reads each line individually, but how do I get it to read and store each data/word from the line (without the comma obviously)?

try{
    BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
    String line = reader.readLine();
    while (line != null){
        System.out.println(line);
        line = reader.readLine();
    }
    reader.close();
} catch(IOException ex){
    System.out.println(ex.getMessage());
}

I saw an example using scanner but I heard that it's slower and less efficient.

I also tried using split but I can't figure out how to do it properly.

Thanks.

Matt
  • 809
  • 1
  • 10
  • 22

3 Answers3

2

You can split the line by the comma , and get an array of values:

   try{
        BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
        String line = reader.readLine();
        String data[] = null;
        while (line != null){
            System.out.println(line);
            line = reader.readLine();
            data = line.split(","); //data will have the values as an array
        }
        reader.close();
    } catch(IOException ex){
        System.out.println(ex.getMessage());
    }
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
2

You can use Files.readAllLines() method and map the data to the dedicated object. Assuming you have such Room object with appropriate constructor you can read and store data like:

List<String> strings = Files.readAllLines(Paths.get("test.txt"));
List<Room> rooms = new ArrayList<>();

for (String line : strings) {
    String[] split = line.split(",");

    Integer roomNumber = Integer.valueOf(split[0]);
    String roomType = split[1];
    Double roomCost = Double.valueOf(split[2]);
    Integer amount = Integer.valueOf(split[3]);
    String bathroom = split[4];

    Room r = new Room(roomNumber, roomType, roomCost, amount, bathroom);
    rooms.add(r);
}

Then you can get the information for some room for example by room number:

Room room = rooms.stream()
        .filter(r -> r.getRoomNumber() == 102)
        .findFirst().orElseThrow(NoSuchElementException::new);

Note: If you are using java10 or above you can use orElseThrow() without parameters

Ruslan
  • 6,090
  • 1
  • 21
  • 36
  • Hi, how exactly do I create the Room object and the appropriate constructure to store the data like you have mentioned? I've been trying to do it for a while now using a Room class but I'm not getting far. I understand how to read the file and each part of the line now but I'm struggling with mapping the data to the object (or making the object itself) and storing the data. Thanks! – Matt Mar 11 '19 at 10:12
  • 1
    @Mandingo You should create a new class `Room` (new file usually). This class should contain properties like `Integer roomNumber`, `String roomType` etc.. And constructor that takes all of them as a parameter. See here for more details and examples https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html – Ruslan Mar 11 '19 at 14:36
  • Ok, so I think I've managed to make the class with the constructor in it (i put a print statement in it and it prints the room information correctly), but how exactly do I store the data and retrieve it? E.g. if I want to bring up data on room 102 how do i do that? – Matt Mar 11 '19 at 18:39
  • 1
    @Mandingo Updated answer with example how to store all rooms to the list and retrieve some specific room by room number – Ruslan Mar 11 '19 at 18:54
  • Is the 'getRoomNumber()' a method that I need to make in the Room class or? – Matt Mar 11 '19 at 19:08
  • 1
    Right, it is get method for room number. `public Integer getRoomNumber() { return roomNumber; }` See more about get/set methods in java https://www.geek-programmer.com/get-and-set-methods-in-java/ – Ruslan Mar 11 '19 at 19:12
  • Thanks, I got it to work fine. One last question, how do I see all of the rooms at the same time? E.g. I want to display all of the rooms on record and their information (after they are stored). – Matt Mar 11 '19 at 22:06
  • 1
    The easiest way is to override the `toString()` method inside Room class. And then print all rooms in a for-loop `for(Room r : rooms) {System.out.println(r); }` See more about `toString` here https://www.javatpoint.com/understanding-toString()-method – Ruslan Mar 11 '19 at 22:13
  • Hi, if you wouldn't mind one more question... How would you recommend me to look up a specific room (by its number) and see if it exists? E.g. I want to see if room 105 exists. I tried using the stream and getRoomNumber == 105 with try and catch but it breaks the code. I also tried using a boolean test using .doesContain(105) with Array and asList but it acts really strange and doesnt fully work. – Matt Mar 13 '19 at 01:35
  • 1
    Hi! I don't mind, but stackOverflow doesn't encourage chatting in the comments. I think it would be better to ask a new question with detailed description your issue and what you've done so far. I'm sure in this case you will get help from me or any other participant of this site. Best regards :) – Ruslan Mar 13 '19 at 19:20
0

If I´m not wrong then the described format is the csv format ( https://en.wikipedia.org/wiki/Comma-separated_values)

Here is good overview how you can read csv data:

https://www.baeldung.com/java-csv-file-array