我正在使用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
}
答案 0 :(得分:0)
下面是一种逐行读取文件的方法。它将打印出所有行,并在遇到*时停止(它还将打印出包含*的行,直到*位置)。同样如前所述,您应该使用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(); }