有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

解析如何在java中解析简单的文本文件

我需要用下面的格式解析一个文本文件,并从文本文件中只提取所需的值。文本文件的内容是

4564444   FALSE  /  TRUE    0   name k0LiuME5Q3
4342222   TRUE  /   TRUE    0   id  ab4454jj

我需要在name和id之后获得值。最好的方法是什么。我在java中使用了Scanner类,但无法获取值。尝试以下代码

Scanner scanner = new Scanner(new File("test.txt"));

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

共 (1) 个答案

  1. # 1 楼答案

    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    public class Read_Text_File {
    
        public static void main(String[] args) {
            System.out.println(getValues());
        }
    
        public static ArrayList<String> getValues() {
            FileInputStream stream = null;
            try {
                stream = new FileInputStream("src/resources/java_txt_file.txt");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String strLine;
            ArrayList<String> lines = new ArrayList<String>();
            try {
                while ((strLine = reader.readLine()) != null) {
                    String lastWord = strLine.substring(strLine.lastIndexOf(" ")+1);
                    lines.add(lastWord);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return lines;
        }
    
    }
    

    Output:

    [k0LiuME5Q3, ab4454jj]