0

How in the shortest amount of lines can you load a file of N lines into an ArrayList of strings.

This is what I have, anyone have any suggestions for how to cut down line count and objects?

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class FileLoad {

    public static void main(String[] args) throws IOException, FileNotFoundException {
        List<String> hs = new ArrayList<String>();
        BufferedReader br = new BufferedReader(new FileReader(args[0]));
        String line;
        while ((line = br.readLine()) != null) {
            hs.add(line);
        }
    }
}
Dan Ciborowski - MSFT
  • 6,807
  • 10
  • 53
  • 88
  • 1
    IMHO this question belongs to http://codereview.stackexchange.com/ – BackSlash Aug 12 '13 at 13:17
  • I'll suggest you to use the interface `List` instead of the implementation `ArrayList`. More information here http://stackoverflow.com/questions/147468/why-should-the-interface-for-a-java-class-be-prefered – Marc-Andre Aug 12 '13 at 13:28

2 Answers2

5

In Java 7+, one line:

List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));
assylias
  • 321,522
  • 82
  • 660
  • 783
1

You can use FileUtils.readLines(File f) method from Apache Commons IO Jar

List<String> lines  = FileUtils.readLines(new File("readme.txt"));
sanbhat
  • 17,522
  • 6
  • 48
  • 64