读取和分割文本文件(Java) [英] Read and split a text file (java)
问题描述
46321882696937; 46322241663603; 358966666
46325844895266; 46326074026933 ; 229131667
46417974251902; 46418206896898; 232644996
46422760835237; 46423223321897; 462486660
现在,我需要文件的第三列,来计算平均值。
我该怎么做?我需要得到每一行文本,然后得到最后一列?
用分隔符分隔一个String,你可以使用split方法,它接收一个正则表达式作为参数,并将所有匹配该表达式的字符序列分割成一个字符串。你的情况很简单,就是 如果你想得到数组的最后一项,你可以使用它的 如果你把所有这些加在一起,你可以得到如下的结果: I have some text files with time information, like: 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 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 And if you want to get the last item of an array you can just use it's And if you join all that together you can get something like this:
这篇关于读取和分割文本文件(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! BufferedReader
或扫描仪
,甚至还有其他一些技术。使用扫描器是非常简单的,就像这样:
pre $ public void read(File file)throws IOException {
Scanner scanner =新的扫描仪(文件); ()。
while(scanner.hasNext()){
System.out.println(scanner.nextLine());
$ b $ p
$ b ;
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);
}
}
46321882696937;46322241663603;358966666
46325844895266;46326074026933;229131667
46417974251902;46418206896898;232644996
46422760835237;46423223321897;462486660
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());
}
}
;
String[] matches = myString.split(";");
length
as parameter. remembering that the last item of an array is always in the index 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);
}
}