读取和分割文本文件(Java) [英] Read and split a text file (java)

查看:191
本文介绍了读取和分割文本文件(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  46321882696937; 46322241663603; 358966666 
46325844895266; 46326074026933 ; 229131667
46417974251902; 46418206896898; 232644996
46422760835237; 46423223321897; 462486660

现在,我需要文件的第三列,来计算平均值。



我该怎么做?我需要得到每一行文本,然后得到最后一列?

解决方案

BufferedReader 扫描仪,甚至还有其他一些技术。使用扫描器是非常简单的,就像这样:

pre $ public void read(File file)throws IOException {
Scanner scanner =新的扫描仪(文件); ()。

while(scanner.hasNext()){
System.out.println(scanner.nextLine());




$ b $ p
$ b

用分隔符分隔一个String,你可以使用split方法,它接收一个正则表达式作为参数,并将所有匹配该表达式的字符序列分割成一个字符串。你的情况很简单,就是;

  String [] matches = myString.split(;); 

如果你想得到数组的最后一项,你可以使用它的长度作为参数。记住数组的最后一个元素总是在索引中 length - 1

  String lastItem = matches [matches.length  -  1]; 

如果你把所有这些加在一起,你可以得到如下的结果:

  public void read(File file)throws IOException {
Scanner scanner = new Scanner(file); ()。

while(scanner.hasNext()){
String [] tokens = scanner.nextLine()。split(;);
String last = tokens [tokens.length - 1];
System.out.println(last);
}
}


I have some text files with time information, like:

46321882696937;46322241663603;358966666
46325844895266;46326074026933;229131667
46417974251902;46418206896898;232644996
46422760835237;46423223321897;462486660

For now, I need the third column of the file, to calculate the average.

How can I do this? I need to get every text lines, and then get the last column?

解决方案

You can read the file line by line using a BufferedReader or a Scanner, or even some other techinique. Using a Scanner is pretty straightforward, like this:

public void read(File file) throws IOException{
    Scanner scanner = new Scanner(file);

    while(scanner.hasNext()){
        System.out.println(scanner.nextLine());
    }
}

For splitting a String with a defined separator, you can use the split method, that recevies a Regular Expression as argument, and splits a String by all the character sequences that match that expression. In your case it's pretty simple, just the ;

String[] matches = myString.split(";");

And if you want to get the last item of an array you can just use it's length as parameter. remembering that the last item of an array is always in the index length - 1

String lastItem = matches[matches.length - 1];

And if you join all that together you can get something like this:

public void read(File file) throws IOException{
    Scanner scanner = new Scanner(file);

    while(scanner.hasNext()){
        String[] tokens = scanner.nextLine().split(";");
        String last = tokens[tokens.length - 1];
        System.out.println(last);
    }
}

这篇关于读取和分割文本文件(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆