want to start reading a file from a specific point - java

I have a file that contains log print out and I want to read certain lines and from certain point from the middle to the end of the line and move to the next line that match the criteria.
I want to start reading from RULE EXECUTING to the end of the line and then check the next line of it has RULE EXECUTING if not skip it to the following line if that does have RULE EXECUTING then copy from that point to the end of the line.
FILE SAMPLE
2013-02-14 09:26:20:078 [main] DEBUG sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd - RULE EXECUTING --> CMNETSL.hdjjjdlskdnlskd.jgfkdflkdfl_Translation
2013-02-14 09:28:00:312 [main] DEBUG moc.uty.lweifoisd.sfsd.kjfdnkjs.RulesetInvoker - Rudejgfjkgjf: After invoking: CMNETSLO
2013-02-14 09:26:20:421 [main] DEBUG sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd - RULE EXECUTING --> sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd
what I want to get from the line would look like this
RULE EXECUTING --> CMNETSL.hdjjjdlskdnlskd.jgfkdflkdfl_Translation
RULE EXECUTING --> sne.ABC.hdhdh.jfjjfj.jkfjfjd.jdsd

So, something like:
BufferedReader br = new BufferedReader(new FileReader("mylog.log"));
String line;
int idx;
while((line = br.getLine()) != null)
if((idx = line.indexOf("RULE EXECUTING --> ")) != -1)
System.out.println(line.substring(idx));
I've not tried that in an ide or compiled it, but I think that you probably get the idea.

Scanner s = new Scanner(new File("log.txt")); // read file using scanner line by line
while(s.hasNextLine())
{
String nextLine = s.nextLine();
if(nextLine.startsWith("RULE EXECUTING")) //check if line starts with the key word
{
// do whatever you want to do
}
}

You have to read the entire file for that, use a FileReader and read the file line for line, searching for the substring "RULE EXECUTING" in each. If it is found, use the substring method to output or otherwise process the substring. Repeat until the file is done and - most importantly - close the file.
Here is a complete codesample:
BufferedReader reader = null;
try {
//open file
reader = new BufferedReader(new FileReader("example.log"));
int index;
//read first line
String line = reader.readLine();
//go through the entire file line for line
while (line != null) {
//look for substring in line
index = line.indexOf("RULE EXECUTING");
if(index >= 0 ) {
//substring found, write result to stdout
System.out.println(line.substring(index));
}
//read next line
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//always close file readers!
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

BufferedReader not reading the entire file and not exiting the loop

I have ini file that to be read in my application but the problem is it is not reading the entire file and it stucks in the while loop.
My code:
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
Properties section = null;
while(line!=null){
if(line.startsWith("[") && line.endsWith("]")){
section = new Properties();
this.config.put(line.substring(1, line.length() - 1), section);
}else{
String key = line.split("=")[0];
String value = line.split("=")[1];
section.setProperty(key, value);
}
line = br.readLine();
System.out.println(line);
// To continue reading newline.
//if i remove this, it will not continue reading the second header
if(line.equals("")){
line = br.readLine();
}
}
System.out.println("Done"); // Not printing this.
This is what inside the ini file. The newlines are included so I add if the line.equals("").
[header]
key=value
[header2]
key1=value1
key2=value2
[header3]
key=value
// -- stops here
//this newlines are included.
#Some text // stops here when I remove all the newlines in the ini file.
#Some text
Output:
[header]
key=value
[header2]
key1=value1
key2=value2
[header3]
key=value
//whitespace
//whitespace
UPDATE:
I remove all the newlines in the ini file but still not reading the entire file.
Unless there's something you've not included in this post the logic won't get stuck in the loop... If the file you're using looks exactly like what you've posted, it'll hit either a blank line(because you're only skipping 1 blank) or one of the lines starting "#" and get an ArrayIndexOutOfBoundsException because those lines don't contain an "="... Simplify your while loop to this and the ArrayIndexOutOfBoundsExceptions wont occur and it'll process the full file:
Properties section = null;
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("[") && line.endsWith("]")) {
section = new Properties();
this.config.put(line.substring(1, line.length() - 1), section);
} else if (line.contains("=") && !line.startsWith("#")) {
String[] keyValue = line.split("=");
section.setProperty(keyValue[0], keyValue[1]);
}
}
Notice that I'm doing a line.contains("=") so that blank lines and lines beginning # are skipped over...

Find String in text file, delete line and ones below

I have a bit of code to find a string in a text file, print the line the string is on and then print the 5 lines below it. However, I need to modify it so that instead of printing, it deletes/removes the line after the string is found. How would I go about doing this?
File file = new File("./output.txt");
Scanner in = null;
try {
in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
if (line.contains("(1)")) {
for (int a = 0; in.hasNextLine() && a < 6; a++) {
System.out.println(line);
line = in.nextLine();
}
}
}
} catch (Exception e) {
}
Find a small snippet you can start with.
Assuming your question.txt has the following input.
line 1
line 2
line 3 (1)
line 4
line 5
line 6
line 7
line 8
line 9
line 10
This snippet will print all lines and skip the line line 3 (1) as well the five lines after.
List<String> lines = Files.readAllLines(Paths.get("question.txt"), Charset.defaultCharset());
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).contains("(1)")) {
i = i + 6;
}
System.out.println(lines.get(i));
}
output
line 1
line 2
line 9
line 10
To store the lines into the file is left for you.
My Suggestion is you first declare and initialise a StringBuilder say output before your above code like:
StringBuilder output = new StringBuilder();
Now after the close of the if statement before the closing of the while loop append the line to the output and add a "\n" at the end like this:
output.append(line+"\n");
Now finally after your code that you have posted create a FileWriter say writer and then use the writer to write the output as shown below:
try(FileWriter writer = new FileWriter(file, false)){
writer.write(output);
}catch IOException(e){
e.printStackTrace();
}
Also don't forget to remove or comment out the following line if you do not want them printed in the output.
System.out.println(line);
SubOtimal has a good, concise answer that will work for most cases. The following is more complex but avoids loading the whole file into memory. That probably isn't an issue for you but just in case...
public void deleteAfter(File file, String searchString, int lineCountToDelete) {
// Create a temporary file to write to
File temp = new File(file.getAbsolutePath() + ".tmp");
try (BufferedReader reader = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new FileWriter(temp)) ) {
// Read up to the line we are searching for
// and write each to the temp file
String line;
while((line = reader.readLine()) != null && !line.equals(searchString)){
writer.println(line);
}
// Skip over the number of lines we want to "delete"
// as well as watching out for hitting the end of the file
for(int i=0;i < lineCountToDelete && line != null; i++){
line = reader.readLine();
}
// Write the remaining lines to the temp file.
while((line = reader.readLine()) != null){
writer.println(line);
}
} catch (IOException e) {
throw new IllegalStateException("Unable to delete the lines",e);
}
// Delete the original file
if(!file.delete()){
throw new IllegalStateException("Unable to delete file: " + file.getAbsolutePath());
}
// Rename the temp file to the original name
if(!temp.renameTo(file)){
throw new IllegalStateException("Unable to rename " +
temp.getAbsolutePath() + " to " + file.getAbsolutePath());
}
}
I tested this with multiple conditions, including a line that doesn't exist, a line at the end and a line with fewer lines left than the number to skip. All worked and gave the appropriate results.

Detect first line of text file separately?

I am designing a program that will load a text file into different media file classes (Media > Audio > mp3, Media > Video > Avi, etc).
Now the first line of my text file is how many files there are in total, as in
3
exmaple.mp3,fawg,gseges
test.gif,wfwa,rgeg
ayylmao.avi,awf,gesg
Now that is what is in my text file, I want to first get the first line separately, then loop through the rest of the files.
Now I understand I can simply count how many files are in by using an int that grows as I loop but I want it clear in the file aswell, and I'm not sure how to go about this.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while(line != null)
{
//Get the first line of the text file seperatly? (Then maybe remove it? idk)
//Split string, create a temp media file and add it to a list for the rest of the lines
}
//String[] split = s.next().split(",");
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
I hope my question is clear, if it TL;DR I want to get the first line of a text file separately, then the rest Id like to loop through.
I wouldn't advice using a for-loop here, since the file might contain additional lines (e.g. comments or blank lines) to make it more human-readable. By examining the content of each line, you can make your processing more robust against this sort of thing.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
String line = reader.readLine(); // <-- Get the first line. You could consider reader as a queue (sort-of), where readLine() dequeues the first element in the reader queue.
int numberOfItems = Integer.valueOf(line); // <-- Create an int of that line.
// Do the rest:
while((line = reader.readLine()) != null) // <-- Each call to reader.readLine() will get the next line in the buffer, so the first time around this will give you the second line, etc. until there are no lines left to read.
{
// You will not get the header here, only the rest.
if(!line.isEmpty() || line.startsWith("#") {
// If the line is not empty and doesn't start with a comment character (I chose # here).
String[] split = line.split(",");
String fileName = split[0];
// etc...
}
}
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
You don't need while loop to read up to end of file. Read first line and convert it to int than loop through.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
int lineNo=Integer.parseInt(reader.readLine());
// Now read upto lineNo
for(int i=0; i < lineNo; i++){
//Do what you need with other lines.
String[] values = reader.readLine().split(",");
}
} catch (Exception e) {
//Your exception handling goes here
}
}

how to remove particular lines when reading text file in java

i want to delete that line where it finds "RxTracker"
this is my text file
INFO http-bio-80-exec-1 root - Received data;863071018134228;12.964624;77.523682;NE;23.22376;3.82;0;2013-01-06^08:41:00;
INFO http-bio-80-exec-1 root - RxTracker; IMEINO is 863071018134228
INFO http-bio-80-exec-2 root - RxTracker Invoked. Reading Parameters
INFO http-bio-80-exec-2 root - Received data;863071018134228;12.964624;77.523682;NE;37.66936;3.82;0;2013-01-06^08:42:52;
INFO http-bio-80-exec-2 root - RxTracker; IMEINO is 863071018134228
INFO http-bio-80-exec-5 root - RxTracker Invoked. Reading Parameters
INFO http-bio-80-exec-5 root - Received data;863071018134228;12.964624;77.523682;NE;20.92728;3.82;0;2013-01-06^08:44:51;
INFO http-bio-80-exec-5 root - RxTracker; IMEINO is 863071018134228
INFO http-bio-80-exec-3 root - RxTracker Invoked. Reading Parameters
this is my java code
public void Insert1()
{
try{
File f=new File("E:/c.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
int lineNum = 0;
String line = null;
while ( (line = br.readLine() ) != null ) {
lineNum++;
if(br.readLine().equalsIgnoreCase("RxTracker"))
{
System.out.println("ji");
}
else
{
System.out.println("ji");
}
//if ( lineNum %2 == 0 ) continue;
//else deal with it
System.out.println(br.readLine());
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e1){
e1.printStackTrace();
}
Try something like this. The code reads each line of a file and writes it to another file.Every time it checks if that line contains RxTracker If that line doesn't contain the RxTracker then it will write that line to the new file and if it contains that string then it will skip that line,
for eg
String lineToRemove = "RxTracker ;
if(!trimmedLine.contains(lineToRemove)) { // check if t he line does not contains it then write it to another file
writer.write(trimmedLine);
writer.newLine();
}

Line when reading a file is empty but the line is not null

I have a problem in java and i dont understand why, since i think i am doing text-book stuff.
An overview in what of want to do is:
I want to create a file that contains in each line two strings: documentPath, documentID (in this format: "documentPath;documentID;")
I want to be able to add lines at the end of the file and load the file to a Java Data Structure, lets say a HashSet.
Each time i want to add a new line, i load all the file in a HashSet, check if the line i want to add is not already there and eventually add it at the end. (small number of data - don't care about efficiency)
The code
Add file:
public void addFile(String documentPath) {
this.loadCollection(); //METHOD IS NOT CONTINUING: ERROR HERE
if (!documentsInfo.contains(documentPath)) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(this.collectionFile, true)));
DocumentInfo documentInfo = new DocumentInfo(documentPath, ++this.IDcounter);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Load file:
public void loadCollection() {
if (loaded) {return;}
BufferedReader br;
try {
br = new BufferedReader(new FileReader(collectionFile));
String line;
while ( (line = br.readLine())!= null ) { //PROBLEM HERE
System.out.println("the line readed from file-" + line + "-");
System.out.println("is the line null: "+ (line==null));
System.out.println("line length: " + line.length());
DocumentInfo documentInfo = new DocumentInfo(line);
documentsInfo.add(documentInfo);
}
br.close();
open = true;
} catch (IOException e) {
e.printStackTrace();
}
}
create the line to add:
public DocumentInfo(String fileLine) {
String delimiter = Repository.DOCUMENT_FILE_SEPARATOR;
StringTokenizer tok = new StringTokenizer(fileLine, delimiter);
System.out.println("Tokenizer starts with string: " + fileLine);
this.documentPath = tok.nextToken(); //EXCEPTION here
this.documentId = Integer.parseInt(tok.nextToken());
}
public String toString() {
String sep = Repository.DOCUMENT_FILE_SEPARATOR;
return this.getDocumentPath()+sep+this.getDocumentId()+sep+"\n";
}
I am getting the exception at the Tokenizer method (java.util.NoSuchElementException) when i try to get the nextToken, but the problem comes from the loadCollection() method. The first time i read the contents of the file nothing is there, the line is empty (lenght: 0) but the line is not null, so the while-condition fails to stop the while iteration.
Here is what i get from the debbuging prints:
the line readed from file--
is the line null: false
line length: 0
Tokenizer starts with string:
Can anyone help me with this?
You get a null only when you have exhausted the stream. But the first line of the stream (your file) is just an empty line - and you load it, the result of the empty line, is an empty string (""). It can be easily solved by skipping lines with string.length() == 0, by adding the following in your while loop:
if (line.length() == 0) continue;
You might want to consider using trim() before checking the length as well, to avoid nasty spaces making the string.length() > 0

Categories

Resources