0

I want to create a method in Java which reads data from a txt file and returns an array. I created the first version of this method - I can say that it works but I have a feeling that the shape of this method is not effective and there is a way to do it much more faster and better... can I ask you to have a look and let me know what can be done better?

thank you very much in advance for your valuable help

    public static String[] reader(File file) throws IOException {
    String array[] = null;
    StringBuilder stringBuilder = new StringBuilder();
    String data;

    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {

        int i = 0;
        while ((data = reader.readLine()) != null) {
            System.out.println("I've just read a line number" + (i + 1));
            i++;

            stringBuilder.append(data + "/");
        }

        if (stringBuilder != null) {
            data = stringBuilder.toString();
            array = data.split("/");
        }

        return array;

    }

}
kendzikq
  • 25
  • 5
  • Don't use a StringBuilder and then split. Use an ArrayList and add the lines to it directly. – Thilo Dec 09 '16 at 12:49
  • Why do you need the null check on `stringBuilder`? – Thilo Dec 09 '16 at 12:49
  • 1
    Unless you really want to write this method, you could also just call `Files.readAllLines(filePath)` (a JDK 8 standard library function). – Thilo Dec 09 '16 at 12:51
  • I'm voting to close this question as off-topic because I believe it is a better fit for the [Code Review Stack Exchange](http://codereview.stackexchange.com/) channel. – Bobulous Dec 09 '16 at 13:01
  • Thank you @Thilo I was looking for a simple solution like this one proposed by you : `Files.readAllLines(filePath)` . This is very helpful ! – kendzikq Dec 09 '16 at 13:24

1 Answers1

0

A much simpler approach is possible since Java8:

public static String[] reader(File file) throws IOException{
    return (String[]) Files.lines(file.toPath()).toArray();
}

If you consent to rather return a List<String> the code is even more straightforward

public static List<String> reader(File file) throws IOException{
    return Files.readAllLines(file.toPath());
}

Thus questioning the need for a method that just encapsulates this instruction. Maybe you could just remove it and call directly Files.readAllLines.

Spotted
  • 3,635
  • 14
  • 33