2012-01-16 54 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