Read and split a text file (java)

拟墨画扇 提交于 2019-11-30 09:10:02

问题


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?


回答1:


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



回答2:


Yes you have to read each line of the file and split it by ";" separator and read third element.



来源:https://stackoverflow.com/questions/15903170/read-and-split-a-text-file-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!