How to discard lines in text file until certain string is found

0 votes
asked May 20, 2013 by oxxi

The file begins with about 200 lines of background information that i don't need. Im trying to skip/ignore those 200 lines until a string is found. Once this string is found I want to be able to continue processing the rest of the text file.

Sample Text File: (up to around line 240 is all the lines i need to skip/ignore) http://pastebin.com/5Ay4ad6y

public static void main(String args[]) { String endOfSyllabus = "~ End of Syllabus"; Path objPath = Paths.get("2014HamTechnician.txt"); if (Files.exists(objPath)) { File objFile = objPath.toFile(); try (BufferedReader in = new BufferedReader(new FileReader(objFile))) { String line = in.readLine(); while (line != null) { line = in.readLine(); } if(endOfSyllabus.equals(line) ){ restOfTextFile = line.split(endOfSyllabus); } } System.out.println(restOfTextFile[0]); } catch(IOException e){ System.out.println(e); } } else{ System.out.println( objPath.toAbsolutePath() + " doesn't exist"); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new A19015_Form().setVisible(true); } });
}

3 Answers

0 votes
answered May 20, 2013 by roridedi

You can try this if you know the exact string that you are looking

if (lineString.startsWith("insert exact string")) { // ...
}
0 votes
answered May 20, 2013 by paul-vargas

What about:

boolean found = false;
for (String line; (line = in.readLine()) != null;) { found = found || line.equals(endOfSyllabus); if (found) { // process line }
}
0 votes
answered Nov 29, 2018 by makky
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class Test { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { List<String> lines = FileUtils.readLines(new File("test.txt")); List<String> avLines = new ArrayList<>(); boolean valid = false; for (String line : lines) { if (line.trim().equals("~ End of Syllabus")) { valid = true; continue; } if (valid) { avLines.add("\n"+line); } } System.out.println(avLines.size()); }
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...