tomaszsvd February 2016

Load Text file into array

Im writing a hotel console program, the problem i have at the moment is to load the saved file back to a String[], when the user presses option to load from file.

The text file includes the guest names saved earlier.

Here is the file data

tom
mo
jo
john
meg
bob
jack
veronica
jessica
angelica

And here is all the code I have

Yes thank you i know arrays are 0 index. for loops are starting from 1 because i want to have Room1 instead Room0 as first

THANK YOU PROBLEM SOLVED

public class FileLoad {
    public String[] readLines(String filename) throws IOException {  
        FileReader fileReader = new FileReader(filename);  

        BufferedReader bufferedReader = new BufferedReader(fileReader);  
        List<String> lines = new ArrayList<String>();  
        String line = null;  

        while ((line = bufferedReader.readLine()) != null) {  
            lines.add(line);  
        }  

        bufferedReader.close();  

        return lines.toArray(new String[lines.size()]);  
    }

public class Hotel_array {

      if (Menu.equalsIgnoreCase("S")) {
                save(hotel); 
            }
            if (Menu.equalsIgnoreCase("L")) {
                load(hotel); 
            }
        }
    }


    private static void save(String hotel[]) {
        try {
            PrintWriter pr = new PrintWriter("data.txt");
            for (int i = 1; i < 11; i++) {
                pr.println(hotel[i]);
            }
            pr.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("No such file exists.");
        }
    }

    public static void load(String[] args) {
        FileLoad rf = new FileLoad();
        String file = "data.txt";
        try {
            String[] hotel = rf.readLines(file);
            for (String line : hotel) {
                System.out.println(line)        

Answers


scsere February 2016

You could change your FileLoad class and add another method to write the array to the file, just to keep all the file IO in one class.

public class FileLoad {

    public static String[] readHotelArray(String filename) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
        List<String> lines = new ArrayList<String>();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }

        bufferedReader.close();

        return lines.toArray(new String[lines.size()]);
    }

    public static void writeHotelArray(String filename, String[] hotel) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename, false));
        //Write each string from the array to the file as a new line
        for (String s : hotel)
            bufferedWriter.write(s + "\n");
        bufferedWriter.flush();
        bufferedWriter.close();
    }
}

Note: Both methods are static so you don't have to instantiate a new object since there will always be only one method call on that object

Now you have to change the way you save and load the array in your Hotel_array class. You could use something like this:

//...
private static void save(String[] hotel) {
    try {
        FileLoad.writeHotelArray("data.txt", hotel);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("No such file exists.");
    }
}

public static String[] load() {
    String file = "data.txt";
    String[] hotelArray = null;
    try {
        hotelArray = FileLoad.readHotelArray(file);
    } catch (IOException e) {
        System.out.println("Unable to create " + file + ": " + e.getMessage());
    }
    return hotelArray;
}
//...

and since parameters in java are always pass-by-value (more about that


jgreve February 2016

tomaszsvd, I will leave this here for your review... I thought it might help your Java learning curve. I encourage you to compare the load() method below with your original code. Also study the example output to see what is different.

fwiw, I like scsere's answer, it is a clean design. You should pursue that and mark it as the answer.


Let's focus on the code for Hotel_array.load( String[] args ).

Once Hotel_array.load() calls rf.readLines() you have 2 arrays in memory.

1st array:  Hotel_array's main()'s local variable "hotel".
2nd array:  load()'s local variable "hotel", which is a temporary variable.

Inside Hotel_array.load() remember that the args parameter ties back to main()'s "hotel" variable.

So load()'s local variable "hotel" has nothing to do with main()'s "hotel" variable.

Just to make this a little more clear I'm going to tweak your load() method:

Sample Output

$ javac *.java
$ cat data.txt 
alpha
beta
gamma
delta
$ java Hotel_array 
WELCOME TO THE HOTEL BOOKING 

Hotel Booking Options
A: To Add customer to a room
V: To View all rooms

E: To Display empty rooms
D: To Delete customer from a room
F: Find room from customer name

O: View rooms alphabetically by name
S: Save to file
L: Load from file
L
Loaded 4 lines from filedata.txt
args[1]=empty, will assign line=alpha
args[2]=empty, will assign line=beta
args[3]=empty, will assign line=gamma
args[4]=empty, will assign line=delta

Hotel Booking Options
A: To Add customer to a room
V: To View all rooms

E: To Display empty rooms
D: To Delete customer from a room
F: Find room from customer name

O: View rooms alphabetically by name
S: Save to file
L: Load from file
V
room 1 is occupied by alpha
room 2 is occupied by beta
room 3 is occupied by gamma
room 4 is occupied by delta
room 5 is empty
room 6 is empty
room 7 is empty
room 8 is empty
room 9 is empty
room 10 is empty

Hotel Booking Option 

Post Status

Asked in February 2016
Viewed 3,105 times
Voted 4
Answered 2 times

Search




Leave an answer