当我必须使用文件阅读器Java时,如何从txt文件填充数组?

时间:2013-05-13 13:33:07

标签: java arrays filereader

我必须使用文本文件中的整数填充数组,我需要文件阅读器从每一行中取一个整数并放入一个数组但是它不能将重复数据放入数组中,这也使得它变得均匀更复杂,重复,我必须把它们写到另一个文本文件,例如:sorted.txt,我无法弄清楚如何在我大学的第一年里做所有这些。如果有人可以提供帮助,我将非常感激。提前谢谢

这是我在方法

中到目前为止所得到的
public static void readFromfile()throws IOException {
    List<String> lines = new ArrayList<String>();
    BufferedReader reader = null;
    try {
     reader = new BufferedReader(new FileReader("file.txt"));
     String line = null;
     while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
} finally {
    reader.close();
}
int[] array = lines.toArray();// i keep getting incopatible type error in this line
awell

在过去的6天里,我正在做这件事,那就是我有多远:(

4 个答案:

答案 0 :(得分:2)

int[] array = lines.toArray();// i keep getting incopatible type error in this line

当然,List<String>#toArray会返回Object[],而不是int[]。 : - )

理想情况下,您可以将列表声明为List<int>(如果数字真的很大,则为List<long>)。不幸的是,至少在Java 6中,你不能这样做,你必须使用List<Integer> / List<Long>。所以这是你的出发点。

然后解析字符串中的数字(例如,来自line)。 Integer.parseInt(或Long.parseLong)可以为您解析。他们的结果分别为intlong,但在添加到列表中时会自动装箱。

或者,您可以查看Scanner class,它是“...一个简单的文本扫描程序,它可以使用正则表达式解析基本类型和字符串......”

int[]列表中获取List<Integer>的最终数组(例如)有点痛苦。如果您可以使用Integer[]代替(并且您可以使用自动装箱/拆箱),那很容易:Integer[] numbers = yourList.toArray(new Integer[yourList.size()]);

如果您确实需要int[],则必须编写一个循环来复制它,或使用类似Apache Commons toPrimitive method的内容。

答案 1 :(得分:0)

使用Scanner类可以简化操作。

List<Integer> numbers = new ArrayList<Integer>();
Scanner s = new Scanner(new FileInputStream("file.txt"));

while (s.hasNextInt()) {
   numbers.add(s.nextInt());
}

答案 2 :(得分:0)

您的问题是,您有一个List of Strings并且您尝试将其转换为int array

作为T.J.克劳德指出,但你不能拥有List<int> - 你必须使用包装类Integer

因此,请将您的列表更改为List<Integer>,然后将其更改为lines.add(Integer.parseInt(line));

答案 3 :(得分:0)

我建议使用Scanner类,它比你正在做的更容易。 该错误是由于将对象分配给整数类型。