Read and split a text file (java)

99封情书 提交于 2019-11-29 13:06:22

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

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

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