2017-10-06 153 views
1

我有txt文件,其中每行包含兩個詞,例如:讀取文件,掃描儀

USA 321 
France 1009 
... 
Germany 902 

我怎樣才能讀取這個文件通過文字在二維數組?我有:

List<List<String>> temps = new ArrayList<>(); 
Scanner dataScanner = new Scanner(dataFile); 

while (dataScanner.hasNextLine()) { 
    Scanner rowScanner = new Scanner(dataScanner.nextLine()); 
    temps.add(new ArrayList<>(2)); 

    while (rowScanner.hasNextLine()) { 
     ... 
    } 
} 
+0

你必須使用掃描儀對該排?如果不是,請使用'String.split()'將行分解成單詞。 –

+0

如果您必須爲該行使用掃描儀,請勿使用'rowScanner.hasNextLine()';它只包含一行。使用'hasNext()'(和'next()')從行中獲取單個單詞。另外,如果你確定每一行總是有2個單詞,你可以使你的結構成爲'List '。 – DodgyCodeException

回答

2

我會做這樣的假設你的代碼工作

List<List<String>> temps = new ArrayList<>(); 
Scanner dataScanner = new Scanner(dataFile); 

while (dataScanner.hasNextLine()) { 
    String[] data = dataScanner.nextLine().split(" "); 
    temps.add(new ArrayList<>(Arrays.asList(data[0],data[1])); 
} 

這需要當前行,並在空格字符將其分解。 此後,它創建了兩個元素的列表,並把它添加到您的臨時工列表

1

如果你想絕對使用掃描儀:

List<List<String>> temps = new ArrayList<>(); 
     Scanner dataScanner = new Scanner("a b\nc d\ne f\n"); 

     while (dataScanner.hasNextLine()) { 
      Scanner rowScanner = new Scanner(dataScanner.nextLine()); 
      List<String> datas=new ArrayList<>(2); 
      temps.add(datas); 

      while (rowScanner.hasNext("[^\\s]+")) { 
       datas.add(rowScanner.next("[^\\s]+")); 
      } 
     } 
1

我的建議是不同的功能在不同的功能總是分開。該代碼變得更容易閱讀,更容易十個分量和可重複使用的

public static List<String> readFileLineByLine(String file) { 
    List<String> lines = new ArrayList<>(); 
    Scanner scanner = new Scanner(file); 
    while (scanner.hasNextLine()) { 
     temps.add(scanner.nextLine()); 
    } 
    return lines; 
} 

public static List<MyData> parseLines(List<String> lines) { 
    List<MyData> list = new ArrayList<>(); 
    for (String line : lines) { 
     String[] data = line.split(" "); 
     list.add(new MyData(data[0], data[1])); 
    } 
    return list; 
} 

(使用List<String>MyData如果需要)

+0

同意你的意見。在你的代碼中,我應該添加一個函數來只讀取一個MyData以增加可維護性和可重用性 – Tuco

1

我掃描器的大風扇,但在這種情況下,您可以逐行讀取並使用String.split。這使用流變得非常簡單。如果你想讀入一個二維數組,你可以這樣做:

try (Stream<String> lines = Files.lines(Paths.get(FILENAME), UTF_8)) { 
     String[][] result = lines.map(s -> s.split("\\s+")) 
           .toArray(String[][]::new); 
    } 

或者,如果你想嵌套列表,你可以這樣做:

try (Stream<String> lines = Files.lines(Paths.get(FILENAME), UTF_8)) { 
     List<List<String>> result = lines.map(s -> s.split("\\s+")) 
             .map(Arrays::asList) 
             .collect(toList()); 
     System.out.println(result); 
    }