读取文件时如何跳过某些文本区域?
How I can to skip some area of text, when reading file?
我正在阅读一个 .txt
文件,并希望在将结果放入 StringBuilder
时跳过本文中的代码列表。
文字示例:
The following Bicycle class is one possible implementation of a
bicycle:
/* The example of Bicycle class class Bicycle {
int cadence = 0;
int speed = 0; } */
这就是我能得出的结论:
public class Main {
public static BufferedReader in;
public static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) {
String input = "input_text.txt";
try {
in = new BufferedReader(new FileReader(input));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String inputText;
try {
while ((inputText = in.readLine()) != null) {
if (inputText.startsWith("/*")) {
// The problem is there:
while (!inputText.endsWith("*/")) {
int lengthLine = inputText.length();
in.skip((long)lengthLine);
}
}
stringBuilder.append(inputText);
}
} catch (IOException e) {
e.printStackTrace();
}
我遇到了无限 while
循环,无法跳到下一行。
您永远不会在 while
循环中重置 inputText
的值,因此它永远不会以 */
结束,从而导致无限循环。此外,您不需要使用 skip()
方法,因为只需阅读这些行,直到遇到 */
即可。尝试将循环更改为:
while (!inputText.endsWith("*/")) {
String temp = in.readLine();
if(temp == null) {break;}
inputText = temp;
}
输出:(打印StringBuilder
)
The following Bicycle class is one possible implementation of a bicycle:
我正在阅读一个 .txt
文件,并希望在将结果放入 StringBuilder
时跳过本文中的代码列表。
文字示例:
The following Bicycle class is one possible implementation of a bicycle:
/* The example of Bicycle class class Bicycle {
int cadence = 0;
int speed = 0; } */
这就是我能得出的结论:
public class Main {
public static BufferedReader in;
public static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) {
String input = "input_text.txt";
try {
in = new BufferedReader(new FileReader(input));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String inputText;
try {
while ((inputText = in.readLine()) != null) {
if (inputText.startsWith("/*")) {
// The problem is there:
while (!inputText.endsWith("*/")) {
int lengthLine = inputText.length();
in.skip((long)lengthLine);
}
}
stringBuilder.append(inputText);
}
} catch (IOException e) {
e.printStackTrace();
}
我遇到了无限 while
循环,无法跳到下一行。
您永远不会在 while
循环中重置 inputText
的值,因此它永远不会以 */
结束,从而导致无限循环。此外,您不需要使用 skip()
方法,因为只需阅读这些行,直到遇到 */
即可。尝试将循环更改为:
while (!inputText.endsWith("*/")) {
String temp = in.readLine();
if(temp == null) {break;}
inputText = temp;
}
输出:(打印StringBuilder
)
The following Bicycle class is one possible implementation of a bicycle: