How to read odd number of lines from a text file using Java?
-
28-09-2019 - |
Question
I have a text file where each odd line holds an integer number (String ofcourse since its in a text file), even lines has a time. I only want to read the numbers, therefore the odd number of lines from a text file. How do I do that?
import java.io.*;
public class File {
BufferedReader in;
String read;
int linenum =12;
public File(){
try {
in = new BufferedReader(new FileReader("MAP_allData.txt"));
for (linenum=0; linenum<20; linenum++){
read = in.readLine();
if(read==null){}
else{
System.out.println(read); }
}
in.close();
}catch(IOException e){ System.out.println("There was a problem:" + e);
}
}
public static void main(String[] args){
File File = new File();
}
}
As of now, it will read all the (odd and even) lines until there is not any more to read from (null)
Since my even number lines is a time stamp like 13:44:23
so can I do something like
if(read==null OR if read includes a time or semi colons ){} else { SOP(read);}
Solution
Surely putting a simple in.readLine ()
just before the close of your for
-loop will sort this out?
i.e.:
for (linenum=0; linenum<20; linenum++) {
read = in.readLine();
if(read==null){}
else{
System.out.println(read);
}
in.readLine ();
}
OTHER TIPS
Read in all lines, and ignore every other one.
int lineNum = 0;
String line = null;
while ( (line = reader.readLine() ) != null ) {
lineNum++;
if ( lineNum % 2 == 0 ) continue;
//else deal with it
}
Or just call readLine()
twice per loop, ignoring the second time, and avoid having a counter (safe since all calls to readLine return null after end-of-stream has been reached).
Edit If efficiency is absolutely key and the date lines had a fixed-length format, you could use skip(15)
or similar to efficiently skip the lines you don't care about.
You already have a linecounter, so if you want to use every other line, use the modulo check
if((linenum % 2) == 1){
System.out.println(read);
}
Just perform something like this each time you read in a line:
String str = read;
char[] all = str.toCharArray();
bool isInt = true;
for(int i = 0; i < all.length;i++) {
if(!Character.isDigit(all[i])) {
isInt = false;
}
else {
isInt = true;
}
}
if isInt {
//INTEGER LINE
} else {
//DO SOMETHING WITH THE TIME
}
This makes the code dynamic. If the text file changes, and integers appear on different numbered lines instead, your code can stay the same.