2012-01-16 53 views
1

在以前的項目中,我需要將文件內容讀入數組。現在我必須做同樣的事情,只有我必須將內容讀入ArrayList。我遇到的一些問題是將文件內容讀入ArrayList

  1. 如何逐步通過ArrayList分別添加每個項目?

  2. 如果文件包含超過10個輸入,它必須退出。我嘗試了以下方法,但無法正常工作。

代碼:

public static String readFile(String fileName) throws IOException { 
    String result = ""; 
    String line = ""; 

    FileInputStream inputStream = new FileInputStream(fileName); 
    Scanner scanner = new Scanner(inputStream); 
    DataInputStream in = new DataInputStream(inputStream); 
    BufferedReader bf = new BufferedReader(new InputStreamReader(in)); 

    int lineCount = 0; 
    String[] numbers; 
    while ((line = bf.readLine()) != null) { 
     numbers = line.split(" "); 

     for (int i = 0; i < 10; i++) { 
      if(i > 10) { 
       System.out.println("The file you are accessing contains more than 10  input values. Please edit the file you wish to use so that it contains" 
         + "> 10 input values. The program will now exit."); 
       System.exit(0); 
      } 

      matrix[i] = Integer.parseInt(numbers[i]); 
     } 
     lineCount++; 

     result += matrix; 
    } 
+3

我看不出有任何的ArrayList。 – 2012-01-16 21:31:12

+0

什麼是矩陣? – hmjd 2012-01-16 21:36:34

+0

這是當前編程,我必須通過一個數組。我的問題是能夠通過一個arrayList。我只是在展示我的背景思維過程。\ – fisherml 2012-01-16 21:41:26

回答

2

if條件總是被false

for (int i = 0; i < 10; i++) { 
    if(i > 10) { 
     System.out.println("The file you are accessing contains more than 10  input values. Please edit the file you wish to use so that it contains" 
         + "> 10 input values. The program will now exit."); 
       System.exit(0); 
    } 

追加到ArrayList使用其add()方法。 ArrayList有一個方法size(),您可以使用它來確定文件是否包含超過10個輸入。

編輯:

for循環的終止條件,應根據numbers.length,而不是十。

3

不是指定的行array[i]的,根本就arrayList.add(line)

如果這不是功課,考慮使用一些第三方的實用工具,比如Apache的公地FileUtils.readLines(..)或番石榴Files.readLines(..)

+0

這是CS241實驗室,所以我不能那樣做。只是尋找如何去做這件事的一般指導。 – fisherml 2012-01-16 21:40:11

+0

不錯,然後看第一段。 – Bozho 2012-01-16 21:42:52

+0

也許我沒有跟着Bozho?關於arrayList.add(行)我試圖將一個字符串存儲到一個Int arrayList中。 – fisherml 2012-01-16 21:56:10