有 Java 编程相关的问题?

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

java有没有办法停止读取特定字符(*)后的行

我正在用Java编程,在遇到一个特定的字符*符号后,我正在努力找到一种停止读取一行的方法

下面是一段代码和我的想法

String reader = buffRead.readLine();
int NUMBER_OF_LINES_IN_FILE = Integer.parseInt(reader);
buffRead.readLine();

for (int counter = 0; counter < NUMBER_OF_LINES_IN_FILE - 2; counter++) {
    String line = buffRead.readLine();
    StringTokenizer Tok = new StringTokenizer(line);
    while (Tok.hasMoreElements())
        System.out.println(Tok.nextElement());
    if (ch == '*') {
        break;
    }

    //Declare a variable (line) and set its value to the line read
    //from the buffRead stream
    print.println(line);
    //Use the println method to write the line to the PrintWriter Buffer
}

共 (1) 个答案

  1. # 1 楼答案

    下面是一种逐行读取文件的方法。它将打印出所有行,并在遇到*时停止(它还将打印出包含*的行,直到*位置)。同样如前所述,您应该使用String类的contains()方法:

    try (BufferedReader reader = new BufferedReader(new FileReader ("/path/to/file"))) {
          String line;
          while ((line = reader.readLine()) != null) {
              if (line.contains("*")) {
                  System.out.println(line.substring(0,line.indexOf("*")));
                  break;
              }
              System.out.println(line);
          }
    } catch (IOException e) { e.printStackTrace(); }