JAVA从txt文件

时间:2017-05-09 20:30:24

标签: java arrays file csv parsing

我一直在尝试将值与文本文件分开。值不是制表符分隔但是变化,我试图将它们放入不同的数组中。文本文件的示例如下所示。

  

1908 1 5.0 -1.4 21 --- 29.7 1908 2 7.3 1.9 8 --- 71.9 1908 3 6.2 0.3   13 --- 101.4 1908 4 8.6 2.1 5 --- 128.6 1908 5 15.8 7.7 0 --- 180.4   1908 6 17.7 8.7 0 --- 196.9 1908 7 18.9 11.0 0 --- 196.1 1908 8 17.5   9.7 0 --- 187.2 1908 9 16.3 8.4 0 --- 99.5 1908 10 14.6 8.0 0 --- 56.1 1908 11 9.6 3.4 6 --- 28.4 1908 12 5.8 0.0 13 --- 10.3 1909 1 5.0 0.1   11 --- 35.6 1909 2 5.5 -0.3 18 --- 49.9 1909 3 5.6 -0.3 17 --- 58.7   1909 4 12.2 3.3 3 --- 188.9 1909 5 14.7 4.8 2 --- 216.8 1909 6 15.0   7.5 0 --- 139.5 1909 7 17.3 10.8 0 --- 151.2 1909 8 18.8 10.7 0 --- 167.5 1909 9 14.5 8.1 0 --- 74.4 1909 10 12.9 6.9 3 --- 101.5

此刻我正在将数据拆分的数组就是这一年;然后,我将为剩余的数据集创建代码。

阵列将是这样的:

yyyy [0] 1908
     [1] 1908
ect
public class test {
    private static String removeCharacters(String string){
        string = string.replace("*", "");
        string = string.replace("#", "");
        string = string.replace("---", "");
        return string;
    }


    public static void main(String[] args) throws IOException {
        int i = 0;
        double test[]= new double [1200];
        BufferedReader testFile = new BufferedReader(new FileReader("historical_weather_data/sources/bradforddata.txt"));
        String line;

        testFile.readLine();
        testFile.readLine();
        testFile.readLine();
        testFile.readLine();
        testFile.readLine();
        testFile.readLine();
        testFile.readLine();

        while((line = testFile.readLine()) != null) { 
            String splits[] = line.split("  ");
            test[i] = Double.parseDouble(removeCharacters(splits[0]));
            i++;
        }
        for(int h=0;h<test.length;++h){
            System.out.println(test[h]);
        }
    }
}

从此代码中产生以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1908   1    5.0    -1.4      21         29.7"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at test.main(test.java:32)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

查看链接文档时,值不是以制表符分隔的,而是使用不同数量的空格。 split方法使用正则表达式,因此这应该有效:

String splits[] = line.split(" +");