Search code examples
javastringstringbuilderstring-parsing

How I can to skip some area of text, when reading file?


I reading a .txt file and want to skip a listing of code in this text, when putting result in StringBuilder.

The example of text:

The following Bicycle class is one possible implementation of a bicycle:

/* The example of Bicycle class class Bicycle {

int cadence = 0;

int speed = 0; } */

So that's what I could come to:

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();
    }

I got the infinity while loop and can't jump to next line.


Solution

  • You never reset the value of inputText in your while loop, so it will never not end with */ resulting in an infinite loop. Also you don't need to use the skip() method as simply reading the lines until you encounter a */ will work. Try changing your loop to:

     while (!inputText.endsWith("*/")) {       
            String temp = in.readLine();
            if(temp == null) {break;}
            inputText = temp;                                                           
     }
    

    Output: (With printing the StringBuilder)

    The following Bicycle class is one possible implementation of a bicycle: