如何解析 java 源代码而不存储空行?

How do I parse through java source code and not store blank lines?

这是我添加每行代码的方法:

    public static void String(){
    File f = new File("src/testClass.java");
    try {
        Scanner s = new Scanner(f);
        s.useDelimiter("\n");
            while(s.hasNextLine()){
                String st = s.next();
                if(!st.equals("\p{Space}")) System.out.println(st);
                }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

这里是testClass.java

public class testClass {
    public static void main (String[] args){
        int someNum = 1; //comment
        String someStr = "haha";
        /* final double pi = 3.14159;
         * 
         */
    }

    public static void uselessMethod(int someNum){
        boolean isUseless1 = true;
    }   
}

当我使用此 class 测试我的解析器时,它不会跳过 main 的右括号下方大括号后的空白 space。需要做什么才能让它不被存储?什么是更合适的 if 语句让它不存储该空行,同时承认它是一行而不是完全跳过它?我想在不存储空行的情况下跟踪行号。

您想使用 matches() 方法而不是 equals():

if(!st.matches("^\p{Space}*$")) System.out.println(st);

我也稍微修改了你的正则表达式。它现在应该排除所有空行或仅包含空格的行。

我通常只是跳过空行:

public static List<String> fileToList(String patch) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(patch));
        String line ="";
        List<String> result = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            /*
             * Just skip empty line
             */
            if (line.isEmpty()) {
                continue;
            } else {
                result.add(line);
            }
        }
        return result;
    }