Home > Net >  Get range of lines in file
Get range of lines in file

Time:10-29

i would like to save in a string multiple lines from reading file, eg: I am reading one file.txt with the following content:

def var x as int.
def var y as char.

procedure something:
    //here some content
end.

I would like to catch content between "procedure" and "end".

public static void main(String[] args) {
        String piContent = "";
        try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if(line.contains("procedure")){
                    piContent = line;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
}

I appreciate any help.

CodePudding user response:

final StringBuilder sb = new StringBuilder();
try (final BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
    String line;
    boolean rememberStuff = false;
    while ((line = br.readLine()) != null) {
        if (line.startsWith("procedure ")) {
            rememberStuff = true;
        } else if (line.startsWith("end.")) {
            rememberStuff = false;
        } else if (rememberStuff) {
            sb.append(line).append('\n');
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
System.err.println("Lines found between procedure and end:");
System.err.println(sb);

CodePudding user response:

public static List<String> getContentFromFile(Path file) throws IOException {
    List<String> res = new ArrayList<>();
    boolean add = false;

    for (String line : Files.readAllLines(file)) {
        if ("end.".equalsIgnoreCase(line.trim()))
            break;
        if (add)
            res.add(line);
        else if ("procedure something:".equalsIgnoreCase(line.trim()))
            add = true;
    }

    return Collections.unmodifiableList(res);
}
  • Related