2015-08-26 48 views
0

我有一個包含整數輸入的兩行不同的文件。我想將第一行整數讀入Arraylist<Integer>,並將第二行輸入讀入其他一些Arraylist。我如何修改下面的代碼來有效地做到這一點。我無法理解如何使用分隔符。將txt文件的不同行讀入不同的ArrayList

import java.util.*; 
import java.io.*; 
public class arr1list { 
    public static void main(String[] args) throws FileNotFoundException { 
     ArrayList<Integer> list1=new ArrayList<Integer>(); 
     File file=new File("raw.txt"); 
     Scanner in=new Scanner(file); 
     Scanner.useDelimiter("\\D"); //the delimiter is not working. 

     while(in.hasNext()) 
      list1.add(in.nextInt()); 
     System.out.println(list1); 
     in.close(); 
    } 
} 
+0

你能指定確切的要求嗎?它的罰款現在只有2個值如果文件中有多個值? –

+0

整數如何相互分離? –

+0

它如何將數據存儲在文件中?你輸入什麼?預期的結果是什麼?你會得到什麼結果? –

回答

0

你可以做一些簡單的像這樣:

try (BufferedReader reader = 
      new BufferedReader(new FileReader("path"));) { 

     List<Integer> first = new ArrayList<>(); 

     for (String number: reader.readLine().split(" ")) { 

      numbers.add(Integer.parseInt(number)); 
     } 

     // do stuff with first and second 

    } catch (IOException ignorable) {ignorable.printStackTrace();} 
} 

BufferedReader.readLine()會照顧文件分隔符解析的爲您服務。

您可以提取採用一行的方法並解析它以創建整數的List。然後是讀取行的兩倍,如上面的reader.readLine(),並調用該方法爲每行生成列表。

0

我會做這樣的事情:

//Arrays are enough because int is a primitive 
int list1[], list2[]; 

try { 
    Scanner in = new Scanner(new FileReader("file.txt")); 

    String line1 = (in.hasNextLine()) ? in.nextLine() : ""; 
    String line2 = (in.hasNextLine()) ? in.nextLine() : ""; 

    String[] line1_values = line1.split(" "); // Split on whitespace 
    String[] line2_values = line2.split(" "); 

    int line1Values[] = new int[line1_values.length], line2Values[] = new int[line2_values.length]; 

    // Map the values to integers 
    for(int i = 0; i < line1_values.length; i++) 
     line1Values[i] = Integer.parseInt(line1_values[i]); 

    for(int i = 0; i < line2_values.length; i++) 
     line2Values[i] = Integer.parseInt(line2_values[i]); 

    in.close();  
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 

我測試了這一點,它工作得很好,其值由空格隔開的文本文件。

1

除了上述的答案,與的java 8風格

BufferedReader reader = Files.newBufferedReader(Paths.get("raw.txt"), StandardCharsets.UTF_8); 
    List<List<Integer>> output = reader 
     .lines() 
     .map(line -> Arrays.asList(line.split(" "))) 
     .map(list -> list.stream().mapToInt(Integer::parseInt).boxed().collect(Collectors.toList())) 
     .collect(Collectors.toList()); 

如導致你將有整數的列表的列表,例如[[1,2,3,4,5〕,〔 6,7,8,9,6]]