Method which is using BufferedReader to read a file and returning an array

时间:2016-12-09 12:46:12

标签: java bufferedreader

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;

    }

}

1 个答案:

答案 0 :(得分:0)

自Java8以来,可以采用更简单的方法:

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

如果您同意返回List<String>,则代码更加直截了当

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

因此质疑是否需要一个只封装该指令的方法。也许您可以将其删除并直接致电Files.readAllLines