2015-06-07 1 views
6

Я хочу прочитать текстовый файл с строкой и несколькими целыми числами, связанными с этой строкой.Получение целочисленных данных из txt-файла в Java

Это класс, который я должен написать свою программу:

public List<Integer> Data(String name) throws IOException { 
    return null; 
} 

Я должен прочитать файл .txt и найти имя в этом файле, с его данными. И сохраните его в ArrayList.

Мой вопрос: как сохранить его в ArrayList<Integer>, когда у меня есть String s в List.
Это то, что я думаю, что я хотел бы сделать:

Scanner s = new Scanner(new File(filename)); 
ArrayList<Integer> data = new ArrayList<Integer>(); 

while (s.hasNextLine()) { 
    data.add(s.nextInt()); 
} 
s.close(); 
+2

Вы хотите превратить строку в целое число? – Alexander

ответ

3

Я бы определил файл в качестве поля (в дополнение к filename, и я предлагаю прочитать его из домашней папки пользователя) file

private File file = new File(System.getProperty("user.home"), filename); 

Затем вы можете использовать оператора алмаза <>, когда вы определяете свой List. Вы можете использовать try-with-resources до closeScanner. Вы хотите читать строки. И вы можете split ваш line. Затем вы проверяете, совпадает ли ваш первый столбец с именем. Если да, то итерация остальных столбцов анализирует их на int. Что-то вроде

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; 
} 

Это может быть signifanctly более эффективно сканировать файл один раз и сохранить имена и поля как Map<String, List<Integer>> как

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; 
} 

Затем сохранить, что в fileContents как

private Map<String, List<Integer>> fileContents = readFile(filename); 

А затем реализуйте свой метод loadDataFor(String) с fileContents как

public List<Integer> loadDataFor(String name) throws IOException { 
    return fileContents.get(name); 
} 

Если ваш шаблон использования читает File для многих имен, то второй, вероятно, будет намного быстрее.

0

Если вы хотите использовать java8, вы можете использовать что-то вроде этого.

input.txt (должен быть в пути к классам):

text1;4711;4712 
text2;42;43 

Код:

public class Main { 

    public static void main(String[] args) throws IOException, URISyntaxException { 

     // find file in classpath 
     Path path = Paths.get(ClassLoader.getSystemResource("input.txt").toURI()); 

     // find the matching line 
     findLineData(path, "text2") 

       // print each value as line to the console output 
       .forEach(System.out::println); 
    } 

    /** searches for a line in a textfile and returns the line's data */ 
    private static IntStream findLineData(Path path, String searchText) throws IOException { 

     // securely open the file in a "try" block and read all lines as stream 
     try (Stream<String> lines = Files.lines(path)) { 
      return lines 

        // split each line by a separator pattern (semicolon in this example) 
        .map(line -> line.split(";")) 

        // find the line, whiches first element matches the search criteria 
        .filter(data -> searchText.equals(data[0])) 

        // foreach match make a stream of all of the items 
        .map(data -> Arrays.stream(data) 

          // skip the first one (the string name) 
          .skip(1) 

          // parse all values from String to int 
          .mapToInt(Integer::parseInt)) 

        // return one match 
        .findAny().get(); 
     } 
    } 
} 

Выход:

42 
43 
Смежные вопросы