Skip every odd line using BufferedReader? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reading certain lines only from input?
Is there a way I can skip every odd line from a file if I am using BufferedReader?

Just read a line and discard it:
BufferedReader bReader = new BufferedReader(new FileReader("someFileName.txt"));
String line = null;
while(true)
{
//skip the odd line
bReader.readLine();
//read an even line
line = bReader.readLine();
if(line != null)
//do stuff with even line
else
break; //end of input
}

BufferedReader br = ...;
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
//do whatever with the data
if (line == null) break;
}

Related

File reader in eclipse

Can anyone tell me why my code never reads the 2nd line of my file? if my 2nd line in the file (for example .txt file) start at a new line and indent that line, it will not read it.But if it is in a new line and it isn't indented , it will read. also it reads 3rd line fine. Is it something with the while loop ?
Scanner keyboard = new Scanner (System.in);
System.out.println("Input the file name");
String fileName = keyboard.nextLine();
File input = new File (fileName);
BufferedReader reader = new BufferedReader(new FileReader(input));
String content = reader.readLine();
content.replaceAll("\\s+","");
while (reader.readLine() != null) {
content = content + reader.readLine();
}
System.out.println(content);
See my comments in the code below.
String content = reader.readLine(); //here you read a line
content.replaceAll("\\s+","");
while (reader.readLine() != null) //here you read a line (once per loop iteration)
{
content = content + reader.readLine(); //here you read a line (once per loop iteration)
}
As you can see, you are reading the second line in the beginning of your while loop, and you are checking if it is equal to null before moving on. However, you do nothing with that value, and it is lost. A better solution would look like this:
String content = ""
String input = reader.readLine();
while (input != null)
{
content = content + input;
input = reader.readLine();
}
This avoids the problem of reading and then throwing away every other line by storing the line in a variable and checking the variable for null instead.
Each time you call readLine() it reads the next line. The statement
while (reader.readLine() != null)
reads a line but does not do anything with it. What you want is
String line;
StringBuilder buf;
while ( (line = reader.readLine()) != null)
{
buf.append(line);
}
content = buf.toString();
Using a StringBuilder is much better as it avoids reallocating and copying the entire string each time you append.

BufferedReader skip lines assets file java android

I'm trying to read a .txt-file that's located in my assets folder in an Android project. Search the file, read the file with the InputStreamer and the BufferedReader works just fine, but the problem is: it doesn't read ALL the lines. So when I want to add a line to an ArrayList for further use, not all the lines are present in this list. This is my code:
InputStream inputStream;
BufferedReader br;
try {
inputStream = getResources().getAssets().open("KeyMapping.txt");
br = new BufferedReader(new InputStreamReader(inputStream));
final ArrayList<String> viewList = new ArrayList<String>();
String line = null;
//Add every line (except the first) to an arrayList
while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char") {
viewList.add(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
The format of my .txt-file is like this:
1,2,3,4,5,6,7,8/char
1,,,,1,,,/a
2,,,,1,,,/b
3,,,,1,,,/c
,1,,,1,,,/d
,2,,,1,,,/e
,3,,,1,,,/f
,,1,,1,,,/g
,,2,,1,,,/h
,,3,,1,,,/i
,,,,1,,,1/j
,,,,1,,,2/k
,,,,1,,,3/l
1,,,,2,,,/m
2,,,,2,,,/n
3,,,,2,,,/o
,1,,,2,,,/p
,2,,,2,,,/q
,3,,,2,,,/r
,,1,,2,,,/s
,,2,,2,,,/t
,,3,,2,,,/u
,,,,2,,,1/v
,,,,2,,,2/w
,,,,2,,,3/x
...
Only a few of these lines will be added to the ArrayList, does anyone know why?
while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char")
This line reads 2 lines from the stream, and processes the 2nd line always.
Also, you cannot compare strings with != operator. Use String.equals() method.
while ((line = br.readLine()) != null)
{
if(line.equals("1,2,3,4,5,6,7,8,char"))
continue;
//add if it's not that string
viewList.add(line);
}

Read all lines with BufferedReader

I want to type a multiple line text into the console using a BufferedReader and when I hit "Enter" to find the sum of the length of the whole text. The problem is that it seems I'm getting into an infinite loop and when I press "Enter" the program does not come to an end. My code is below:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line= buffer.readLine();
while (line!=null){
length = length + line.length();
line= buffer.readLine();
}
Could you please tell me what I'm doing wrong?
One line of code using Java 8:
line = buffer.lines().collect(Collectors.joining());
The idiomatic way to read all of the lines is while ((line = buffer.readLine()) != null). Also, I would suggest a try-with-resources statement. Something like
try (InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream)) {
long length = 0;
String line;
while ((line = buffer.readLine()) != null) {
length += line.length();
}
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
If you want to end the loop when you receive an empty line, add a test for that in the while loop
while ((line = buffer.readLine()) != null) {
if (line.isEmpty()) {
break;
}
length += line.length();
}
JLS-14.15. The break Statement says
A break statement transfers control out of an enclosing statement.
line will not be null when you press enter; it will be an empty string.
Take note of what the BufferedReader JavaDoc says about readLine():
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
And readLine() returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So when you press [Enter], you are giving the BufferedReader a new line containing only \n, \r, or \r\n. This means that readLine() will return an empty string.
So try something like this instead:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line = buffer.readLine();
while( (line != null) && (!line.isEmpty()) ){
length = length + line.length();
line = buffer.readLine();
}
When you only press Enter the return from buffer.readLine(); isn't null it is an empty String.
Therefore you should change line != null to !line.equals("") (You could also change it to line.length() > 0)
Now your code will look something like this:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line = buffer.readLine();
while (!line.equals("")){
length = length + line.length();
line = buffer.readLine();
}
This should solve your problem. Hope this helped! :)
Since Java 8 you can use BufferedReader#lines method directly on buffered reader.
try (InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in)) {
final int length = buffer.lines().mapToInt(String::length).sum();
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
Snarky answer: what you're doing wrong is only creating 2 objects in Java to do something... if you search, you can probably find a few more classes that extend BufferedReader or ExtendedBufferReader etc., and then it can be real Enterprise Java.
Now that i've gotten that out of my system: more useful answer. System.in is closed when you input EOF, which is Control-D under Linux and I think MacOS, and I think Control-Z plus enter under Windows. If you want to check for enter (or more specifically, two enters... one to finish the last line and one to indicate that you're done, which is essentially how http handles determining when the http headers are finished and it's time for the http body, then #dbank 's solution should be a viable option with a minor fix I'm going to try to make to move the ! inside the while predicate instead of !while.
(Edit #2: realized readLine strips the newline, so an empty line would "" instead of the newline, so now my code devolves to another answer with the EOF bit as an answer instead of comment)
Edit... that's weird, #dbank had answered while I was typing my answer, and I would have stopped had I not though mentioning the EOF alternative. To repeat his code from memory with the edit I was going to make:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line= buffer.readLine();
while (line != null && !line.equals("")){
length = length + line.length();
line= buffer.readLine();
}
Put every lines into String[] array. and second method get the number of lines contains in text file. I hope this might be useful to anyone..
public static void main(String... args) throws IOException {
String[] data = getLines();
for(String v : data) {
out.println(v);
}
}
public static String[] getLines() throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = bufferReader.readLine();
String[] data = new String[getLinesLength()];
int i = 0;
while(line != null) {
data[i] = line;
line = bufferReader.readLine();
i++;
}
bufferReader.close();
return data;
}
public static int getLinesLength() throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = bufferReader.readLine();
int size = 0;
while(line != null) {
size += 1;
line = bufferReader.readLine();
}
bufferReader.close();
return size;
}
Good example from #Russel Yang (https://stackoverflow.com/a/40412945/11079418).
Use this code, to add also a new line character after each line.
String lines = bufferedReader.lines().map(line -> line + "\n").collect(Collectors.joining());

How to read data from System.in to solve the task?

I'm working on this item. I did the spell checking algorithm but I have no idea how to read data correctly. When I use this:
StringBuilder text = new StringBuilder();
Scanner sc = new Scanner(System.in);
String temp;
while ((temp = sc.nextLine()).length() > 0){
text.append(temp);
}
/*spell checking algorithm*/
It waits for the empty string.
In this case:
while (sc.hasNext()){
text.append(temp);
}
it doesn't continue to execute the code at all. If I try to read 10000 signs I should type it all.
How could I read data correctly for this task?
Read them from file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
//do what you want
}

using BufferedReader in Java

How can I use BufferedReader for reading all lines between two concrete line. for example i want to start reading from line1 то line2, can I use this code
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line1 = "StartLine";
String line2 = "EndLine";
while (!line1.equals(line2))
{
// do something
line1 = reader.readLine();
}
I write something like this, but it does not working! Please help me, I am beginner in Java!
Change the loop in following way. You need to read the line in condition and check if it's not nutll i.e. end of file.
String line1 = "StartLine";
String line2 = "EndLine";
String line3 = null;
//Iterate upto line1
while( (line3 = reader.readLine()) != null && ! line3.equals(line1));
//Print the lines till line2
while(line3 != null && ! line3.equals(line2) ) {
System.out.println(line3);
line3 = reader.readLine();
}
First you need another loop to read all lines BEFORE your "StartLine"
and then you will need to be more specific about what is NOT working.
What you expect to happen and what is not happening
You can try using BufferReader's mark and reset methods:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line1 = "StartLine";
String line2 = "EndLine";
String line;
while ((line = reader.readLine()) != null) {
if (line1.equals(line)) {
System.out.println(line);
reader.mark(100);
}
}
reader.reset();
while ((line = reader.readLine()) != null) {
if (line2.equals(line)) {
break;
} else {
System.out.println(line); //or whatever you want to do
}
}
}
You might have to play with the mark value, but something like this might work for you.
Hope that helps.

Categories