Unexpected Buffered Reader Behavior: skipping odd-numbered lines [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am experiencing very strange behavior with BufferedReader. I want to read an entire file however it only reads every other line.
E.g the file below
1 //ignore the left most space - shouldn't exist
2
3
4
5
6
Will output
2
4
6
Here is some of my code...
fileRead = new BufferedReader(new InputStreamReader( new FileInputStream(file)));
public void scan(){
if (fileRead != null){
try{
while ((fileRead.readLine()) != null){
String line = fileRead.readLine();
String abcLine = line;
System.out.println(line);
}
}catch(IOException e) {
System.out.println("Line can not be read");
}
}else{ System.out.println("Can not Read - File Not Found"); }
}
My best bet is the bug lies within the while statement. Is this the correct way to ensure
you read the file until you reach EOF "end of file" ?
Any insight is truly appreciated
Thank you!

You're reading two lines each time through the loop. Your current code is:
while ((fileRead.readLine()) != null){ // reads a line, ignores it
String line = fileRead.readLine(); // reads another line, stores in 'line'
... // do stuff with 'line'
}
Every call to readLine() reads a line. You probably want something more like:
String line;
while ((line = fileRead.readLine()) != null) {
... // do stuff with 'line'
}

Related

How do i read multiple lines of input via the BufferedReader? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am developing a program that takes input from the console. So far it has been no problem reading input that consists of one line of input from the console. But the program does not work when it is supposed to read multiple lines. How can i improve the readInput method to read multiple lines of input and the return a single String containing all of the input from different lines.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
String input = inputstream.readLine();
return input;
}
So when you write String input = inputstream.readLine() This reads one line at a time,
As you are taking input from the user there would not be any null cases even if the user clicks enter, You need to check for the length of the input string, If it is 0 then break from the while loop.
But this isn't the case when you are reading from a file or other source you need to check whether the input is null or not.
Hope this could help you.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
StringBuilder finalString = new StringBuilder();
String input = inputstream.readLine();
while(true){
finalString.append(input);
input=inputstream.readLine();
if(input.length() == 0){
break;
}
}
br.close();
return finalString;
}
Input:
hi hello
how are you
Am fine
Output:
hi hellohow are youAm fine

Converting String element to Integer java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am writing a method which takes in a .txt file and adds the information to a Student type, which has String name and int age, weight and height. I load in all the data, splitting by a comma. To convert the string to int I am trying to use Integer.pareseInt(), but this code seems to be causing an error, what might be causing this?
public static StudentCollection loadBespoke(File file){
List<Student> students = new ArrayList<>();
try (BufferedReader b_reader = new BufferedReader(new FileReader(file))){
String line;
while((line = b_reader.readLine())!= null){
String[] items = line.split(",");
String name = items[0];
System.out.println(items[1]);
int age = Integer.parseInt(items[1]); //errors
int weight = Integer.parseInt(items[2]);
int height = Integer.parseInt(items[3]);
Student student = new Student();
student.withName(name);
student.withAge(age);
student.withWeight(weight);
student.withHeight(height);
students.add(student);
}
} catch (IOException e) {
e.printStackTrace();
} return new StudentCollection(students);
}
The .txt looks like this:
Benjamin, 20, 63, null
Sarah, 19, 53, 165
And the error is:
Exception in thread "main" java.lang.NumberFormatException: For input string: " 20"
Remove spaces between elements or trim the items Integer.parseInt(items[1].trim())
Make sure items[1] has no space or tab to it.. try printing its value.. in Java you can trim using trim() method

Loading an int and an encrypted String from txt file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am working on the password login portion of a class project. Nothing fancy. User, or role will be an int and password is a String. I am just using a simple encryption for now. The problem I am having is while reading the file I am getting an input mismatch. I have done something similar in the past that required me to read ints and Strings and did not have any problems. But I just cannot figure out what is going wrong in this case. Any help as to why I am getting this error would be greatly appreciated. I am using while(inputStream.hasNextLine()) then read the int and then the String I have tried hasNextInt and hasNext and keep getting the same error.
public void readFile(){
Scanner inputStream = null;
try {
inputStream = new Scanner (new FileInputStream("login.txt"));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
if(inputStream != null){
while (inputStream.hasNextLine()){
int luser = inputStream.nextInt();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count ++;
}
inputStream.close();
}
}
Try reading it as a String and converting the string to an int
while (inputStream.hasNextLine()) {
Integer luser = Integer.parseInt(inputStream.nextLine());
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count++;
}
But you need to make sure your file has your data in the exact format as below
12342
password
It's hard to say without knowing what error it is that you are getting, but my guess is that it is because you are not reading the entire file.
Your file probably looks like this:
1\r\n
password\r\n
When you call nextInt() it reads the int, but doesn't advance past the first \r\n so when you call nextLine() it reads to the end of the line so all you get is \r\n. You need to read past the first \r\n and then read the password.
Try
int luser = inputStream.nextInt();
inputStream.nextLine();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);

Trouble opening text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have some trouble reading a file. I have my input.txt in contents package, but the program still can't open the file.
String line = null;
try{
//loen faili
FileReader fileReader = new FileReader("contents/input.txt");
BufferedReader buffReader = new BufferedReader(fileReader);
while((line = buffReader.readLine()) != null){
System.out.println(line);
}
buffReader.close();
}catch(FileNotFoundException ex){
System.out.println("Error opening file");
}catch(IOException ex){
System.out.println("Error reading file");
}
Because you need to differnetly open files from your app packages than the one from disk, try:
InputStream is = getClass().getClassLoader().getResourceAsStream("contents/input.txt");

Retrieving a string by line number? Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have 3 text files that all contain strings from objects.
I have a GUI with a list that is populated with the contents of one text file. Im currently looking to implement something that would take the line number from the first file and pull out the strings from the same line number in other files. Can anyone recommend anything?
You can use:
String[] lines = secondFileText.split("\n");
P.s.- If that doesn't work try replacing \n with \r\n.
You can split a string into lines:
String[] lines = s.split("\r?\n");
Then you can access the line at any index:
System.out.println(lines[0]); // The array starts at 0
Note: On Windows, the norm for ending lines is to use a carriage-return followed by a line-feed (CRLF). On Linux, the norm is just LF. The regular expression "\r?\n" caters for both cases - it matches zero or one ("?") carriage-returns ("\r") followed by a line-feed ("\n").
BufferedReader will deal well with huge files that won't fit in memory, it's pretty fast and deal with both \r and \n
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadByLine {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
File f = new File("xyz.txt");
int lineNumber = 666;
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
int count = -1;
try {
while((line = br.readLine())!=null){
count++;
if (count == lineNumber){
//get the line, do what you want
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
} catch (IOException e) {
br = null;
}
}
//do what you want with the line
}
}

Categories

Resources