I would define the file as a field (in addition to filename , and I suggest reading it from the user's home folder) file
private File file = new File(System.getProperty("user.home"), filename);
Then you can use the diamond operator <> when you define your List . You can use try-with-resources to close your Scanner . You want to read lines. And you can split your line . Then you check to see if your first column matches the name. If so, try again and other columns will parse them before int . Sort of
public List<Integer> loadDataFor(String name) throws IOException { List<Integer> data = new ArrayList<>(); try (Scanner s = new Scanner(file)) { while (s.hasNextLine()) { String[] row = s.nextLine().split("\\s+"); if (row[0].equalsIgnoreCase(name)) { for (int i = 1; i < row.length; i++) { data.add(Integer.parseInt(row[i])); } } } } return data; }
Perhaps itβs much more efficient to scan the file once and save the names and fields as Map<String, List<Integer>> as
public static Map<String, List<Integer>> readFile(String filename) { Map<String, List<Integer>> map = new HashMap<>(); File file = new File(System.getProperty("user.home"), filename); try (Scanner s = new Scanner(file)) { while (s.hasNextLine()) { String[] row = s.nextLine().split("\\s+"); List<Integer> al = new ArrayList<>(); for (int i = 1; i < row.length; i++) { al.add(Integer.parseInt(row[i])); } map.put(row[0], al); } } catch (Exception e) { e.printStackTrace(); } return map; }
Then save this as fileContents as
private Map<String, List<Integer>> fileContents = readFile(filename);
And then implement your loadDataFor(String) method with fileContents like
public List<Integer> loadDataFor(String name) throws IOException { return fileContents.get(name); }
If your usage pattern reads file for many names, then the second is likely to be much faster.
source share