【问题标题】:java file int array readjava文件int数组读取
【发布时间】:2014-04-06 18:54:11
【问题描述】:

我想从文件中获取一个整数数组。但是当我得到一个数组时,数组中有不需要的零,因为大小为 10,文件中只有 5 个整数(18、12、14、15、16 )。如何删除那些零。 代码是:

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;



public class TxtFile {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    File inFile=new File("H:\\Documents\\JavaEclipseWorkPlace\\ReadTextFile\\src\\txt.txt");
    Scanner in=null;
    int []contents = new int[10];
    int i=0;
    try {
        in=new Scanner(inFile);

        while(in.hasNextInt()){
             contents[i++]=in.nextInt();
        }
        System.out.println(Arrays.toString(contents));
    }
    catch(IOException e){
        e.printStackTrace();
    }
    finally{
        in.close();
    }

}

}

输出是: [18、12、14、15、16、0、0、0、0、0]。

【问题讨论】:

  • 如果我想通过插入排序然后执行二分查找可以完成(在ArrayList上)吗?

标签: java arrays file


【解决方案1】:

这是因为你分配了一个大小为 10 的数组,并且值默认初始化为 0。然后从文件中读取 5 个值,这只会覆盖数组中的前 5 个值,未触及的 0 仍然存在。

你有几个选择:

您可以计算从文件中读取的值的数量,然后调整数组大小以匹配,例如:

while(in.hasNextInt()){
    contents[i++]=in.nextInt();
}

// 'i' now contains the number read from the file:
contents = Arrays.copyOf(contents, i);
// contents now only contains 'i' items.
System.out.println(Arrays.toString(contents));

您可以计算从文件中读取的值的数量,然后仅显式打印那么多值,例如:

while(in.hasNextInt()){
    contents[i++]=in.nextInt();
}

// 'i' now contains the number read from the file:
for (int n = 0; n < i; ++ n)
    System.out.println(contents[n]);

您可以使用像ArrayList&lt;Integer&gt; 这样的动态容器,并在读取它们时简单地向其中添加值。然后您可以自动支持文件中的任何数字,例如:

ArrayList<Integer> contents = new ArrayList<Integer>();

...
while(in.hasNextInt()){
    contents.add(in.nextInt());
}

System.out.println(contents);

我推荐第三个选项。这是最灵活和最容易处理的。

【讨论】:

  • 谢谢兄弟。我对此表示赞赏。
【解决方案2】:

将输入文件读入ArrayList&lt;Integer&gt;,然后调用toArray返回一个整数数组

【讨论】:

    【解决方案3】:

    您可以为此使用动态向量

    import java.io.File;
    import java.io.IOException;
    import java.util.*;
    class St{
     public static void main(String args[]){
     File inFile=new File("H:\\Documents\\JavaEclipseWorkPlace\\ReadTextFile\\src\\txt.txt");
    Scanner in=null;
    Vector<Integer> arr=new Vector<Integer>(5,2); //5 is initial size of vector, 2 is increment in size if new elements are to be added
    try {
        in=new Scanner(inFile);
    
        while(in.hasNextInt()){
             arr.addElement(in.nextInt());
        }
    arr.trimToSize(); // This will make the vector of exact size
        System.out.println(arr.toString());
    }
    catch(IOException e){
        e.printStackTrace();
    }
    finally{
        in.close();
    }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      相关资源
      最近更新 更多