2015-06-07 15 views
6

Tôi muốn đọc tệp văn bản có Chuỗi và một vài số nguyên liên quan đến chuỗi đó.Lấy dữ liệu nguyên từ tệp txt trong Java

Đây là lớp học mà tôi phải viết chương trình của tôi trong:

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

tôi phải đọc file .txt và tìm tên trong tập tin đó, với dữ liệu của nó. Và lưu nó vào một ArrayList.

Câu hỏi của tôi là làm thế nào để lưu nó trong ArrayList<Integer> khi tôi có String s trong List.
Đây là những gì tôi nghĩ rằng tôi sẽ làm:

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

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

Bạn muốn biến String để số nguyên? – Alexander

Trả lời

3

tôi sẽ xác định các tập tin như một lĩnh vực (ngoài các filename, và tôi khuyên bạn nên đọc nó từ thư mục nhà của người dùng) file

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

Sau đó, bạn có thể sử dụng toán tử kim cương <> khi bạn xác định List. Bạn có thể sử dụng try-with-resources đến closeScanner của mình. Bạn muốn đọc theo dòng. Và bạn có thể splitline của mình. Sau đó, bạn kiểm tra xem cột đầu tiên của bạn có khớp với tên không. Nếu có, lặp lại các cột khác sẽ phân tích cú pháp chúng thành int. Một cái gì đó như

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

Nó có thể là signifanctly hiệu quả hơn để quét các tập tin một lần và lưu trữ các tên và các lĩnh vực như một Map<String, List<Integer>> như

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

Sau đó lưu trữ mà như fileContents như

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

Và sau đó triển khai phương pháp loadDataFor(String) của bạn với fileContents như

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

Nếu mẫu sử dụng của bạn đọc File đối với nhiều tên thì thứ hai có thể sẽ nhanh hơn nhiều.

0

Nếu bạn muốn sử dụng java8, bạn có thể sử dụng một cái gì đó như thế này.

INPUT.TXT (phải là trong classpath):

text1;4711;4712 
text2;42;43 

Mã:

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

Sản lượng:

42 
43 
Các vấn đề liên quan