安卓java文本分割,读取和分割文本文件(Java)

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值