2014-03-04 56 views
3

我想从包含100,000个双打的文件读取双精度,排列成两个双精度线,每个用空格分隔。就像这样:如何从.txt文件读取双精度到一个ArrayList

2.54343 5.67478 
1.23414 5.43245 
7.64748 4.25536 
... 

到目前为止我的代码:此代码运行

Scanner numFile = new Scanner(new File("input100K.txt").getAbsolutePath()); 
ArrayList<Double> list = new ArrayList<Double>(); 
while (numFile.hasNextLine()) { 
    String line = numFile.nextLine(); 
    Scanner sc = new Scanner(line); 
    sc.useDelimiter(" "); 
    while(sc.hasNextDouble()) { 
     list.add(sc.nextDouble()); 
    } 
    sc.close(); 
} 
numFile.close(); 
System.out.println(list); 
} 

后,它打印到控制台和空的ArrayList [],我想不通为什么。

从文件中删除getAbsolutePath()给了我这一行:

Scanner numFile = new Scanner(new File("input100K.txt")); 

但是当我运行程序时,它给我一个FileNotFoundException异常。我知道该文件存在,我可以看到并打开它。

input100K.txt与程序一起位于src包文件夹中。有没有特定的地方文件必须为此工作?

编辑:作为叶夫根尼·Dorofeev指出,该文件需要在程序找到它的项目文件夹(src文件夹的母公司)。

+3

看起来像你没有找到预期的文件。尝试将文件的绝对路径或打印出来,然后再阅读它以检查它是否存在。 –

+0

我肯定会在开始时添加一个检查以确保文件存在并且可读,它可能非常像@LuiggiMendoza所说的那样,它没有找到该文件。 – Taegost

回答

4

当您创建像这样的扫描仪new Scanner(new File("input100K.txt").getAbsolutePath());您正在扫描文件路径作为输入而不是文件本身。这样做new Scanner(new File("input100K.txt"));

+0

这样做,我现在得到一个'FileNotFoundException'。有没有一个特定的地方,该文件应该在我的电脑上?现在,它在我的src包文件夹中,也包含该程序。 – Kestrel

+1

尝试将其放置在项目文件夹 –

+0

这就是问题所在。谢谢。 – Kestrel

0

你可以尝试使用split()方法刚刚读取的行,然后解析每个部分到double。请注意,这不是必要建立两个Scanner S:

Scanner sc = new Scanner(new File("input100K.txt")); 
sc.useDelimiter(" "); 
ArrayList<Double> list = new ArrayList<Double>(); 

while (sc.hasNextLine()) { 
    String[] parts = sc.nextLine().split(" "); // split each line by " " 
    for (String s : parts) { 
     list.add(Double.parseDouble(s)); // parse to double 
    } 
} 
sc.close(); 

System.out.println(list); 
0

更换线

Scanner numFile = new Scanner(new File("input100K.txt").getAbsolutePath()); 

Scanner numFile = new Scanner(new File("input100K.txt")); 
0

下面是一个简单的程序:

public static void main(String[] args) throws FileNotFoundException { 

     List<Double> doubleList = new ArrayList<Double>(); 
     Scanner scanner = new Scanner(new File("/home/visruthcv/inputfile.txt")); 
     while (scanner.hasNextDouble()) { 

      double value = scanner.nextDouble(); 

      System.out.println(value); 

      doubleList.add(value); 

     } 
     /* 
     * for test print 
     */ 
     for (Double eachValue : doubleList) { 
      System.out.println(eachValue); 
     } 

    }