如何从Java中的文本文件中读取逗号分隔值?

时间:2012-06-09 10:27:25

标签: java string io

我有这个文本文件,其中包含地图上不同点的纬度和经度值。

如何将弦乐分成纬度和经度?与其他分隔符(如空格或制表符等)一起执行这些类型的事物的一般方法是什么? 样本文件:

28.515046280572285,77.38258838653564
28.51430151808072,77.38336086273193
28.513566177802456,77.38413333892822
28.512830832397192,77.38490581512451
28.51208605426073,77.3856782913208
28.511341270865113,77.38645076751709

这是我用来从文件中读取的代码:

try(BufferedReader in = new BufferedReader(new FileReader("C:\\test.txt"))) {
    String str;
    while ((str = in.readLine()) != null) {
        System.out.println(str);
    }
}
catch (IOException e) {
    System.out.println("File Read Error");
}

5 个答案:

答案 0 :(得分:27)

您可以使用String.split()方法:

String[] tokens = str.split(",");

之后,使用Double.parseDouble()方法将字符串值解析为double。

double latitude = Double.parseDouble(tokens[0]);
double longitude = Double.parseDouble(tokens[1]);

其他包装类中也存在类似的解析方法 - IntegerBoolean等。

答案 1 :(得分:4)

使用OpenCSV获得可靠性。拆分不应该用于这类事情。 这是我自己的程序片段,非常简单。我检查是否指定了分隔符,如果是,则使用此分隔符,如果不是,则使用OpenCSV中的默认值(逗号)。然后我读了标题和字段

CSVReader reader = null;
try {
    if (delimiter > 0) {
        reader = new CSVReader(new FileReader(this.csvFile), this.delimiter);
    }
    else {
        reader = new CSVReader(new FileReader(this.csvFile));
    }

    // these should be the header fields
    header = reader.readNext();
    while ((fields = reader.readNext()) != null) {
        // more code
    }
catch (IOException e) {
    System.err.println(e.getMessage());
}

答案 2 :(得分:1)

要用逗号分隔字符串(,),请使用str.split(",")并使用标签str.split("\\t")

    try {
        BufferedReader in = new BufferedReader(
                               new FileReader("G:\\RoutePPAdvant2.txt"));
        String str;

        while ((str = in.readLine())!= null) {
            String[] ar=str.split(",");
            ...
        }
        in.close();
    } catch (IOException e) {
        System.out.println("File Read Error");
    }

答案 3 :(得分:0)

o / p格式的

ng-pattern="/^[\w -!@#$%^&\*()\+]*$/" /> 正在显示

//lat=3434&lon=yy38&rd=1.0&|

答案 4 :(得分:0)

您也可以使用java.util.Scanner类。

private static void readFileWithScanner() {
    File file = new File("path/to/your/file/file.txt");

    Scanner scan = null;

    try {
        scan = new Scanner(file);

        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            String[] lineArray = line.split(",");
            // do something with lineArray, such as instantiate an object
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        scan.close();
    }
}
相关问题