gpt4 book ai didi

java - 读取文件时如何跳过某些文本区域?

转载 作者:行者123 更新时间:2023-12-01 19:49:59 25 4
gpt4 key购买 nike

我正在读取 .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:

关于java - 读取文件时如何跳过某些文本区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51748663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com