Reading CSV file using BufferedReader resulting in reading alternative lines - java

I'm trying to read a csv file from my java code. using the following piece of code:
public void readFile() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
lines = new ArrayList<String>();
String newLine;
while ((newLine = br.readLine()) != null) {
newLine = br.readLine();
System.out.println(newLine);
lines.add(newLine);
}
br.close();
}
The output I get from the above piece of code is every alternative line [2nd, 4th, 6th lines] is read and returned by the readLine() method. I'm not sure why this behavior exists. Please correct me if I am missing something while reading the csv file.

The first time you're reading the line without processing it in the while loop, then you're reading it again but this time you're processing it. readLine() method reads a line and displaces the reader-pointer to the next line in the file. Hence, every time you use this method, the pointer will be incremented by one pointing to the next line.
This:
while ((newLine = br.readLine()) != null) {
newLine = br.readLine();
System.out.println(newLine);
lines.add(newLine);
}
Should be changed to this:
while ((newLine = br.readLine()) != null) {
System.out.println(newLine);
lines.add(newLine);
}
Hence reading a line and processing it, without reading another line and then processing.

You need to remove the first line in a loop body
newLine = br.readLine();

In java 8, we can easily achieve it
InputStream is = new ByteArrayInputStream(byteArr);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
List<List<String>> dataList = br.lines()
.map(k -> Arrays.asList(k.split(",")))
.collect(Collectors.toCollection(LinkedList::new));
outer list will have rows and inner list will have corresponding column values

Related

How to store multiple lines from file into String from Scanner `

Using Scanner, i'm not sure how to read a file with multiple lines and store it all into a String. I use a loop like :
while(file.hasNext())
{
string += file.nextLine();
}
I find that the file.hasNext method eats up all of the data in the file and so file.nextInt() doesn't have any values to find and so it returns and error. What can I do to "reset" the Scanner? I tried creating a new Scanner object but that didn't change anything. I have to run this string through a method and I have run into this problem many times. What should I do?
Maybe you should try StringBuilder.
StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
builder.append(line);
// process the line.
}
}
later
String text = builder.toString();
To read the entire contents of a Scanner source into a String, set the Scanner's delimiter to the end of the file:
String contents = file.useDelimiter("\\Z").next();

use bufferedreader on a txt file twice?

i have to count the lines on a file but later in the code I also have to print what's in that file, but I can't use the reader twice it just says null. How can I work this out without creating a bunch of bufferedreader objects?
thanks
Print and count at the same time?
Move the lines to an array then print them?
Make sure you've closed the file before reopening again?
Try closing the buffer, and then re-opening it again.
BufferedReader bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));
String line = bufferedReader.readLine();
int lineCount = 0;
while(line != null){
lineCount += 1;
line = bufferedReader.readLine();
}
System.out.println("Line count is: " + lineCount);
bufferedReader.close();
bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));
line = bufferedReader.readLine();
while(line != null){
System.out.println(line);
line = bufferedReader.readLine();
}
}
You can use BufferedReader's mark() and reset() methods to jump back to a specific position.
try (BufferedReader r = new BufferedReader(new FileReader("somefile.txt"))) {
// marks this position for the next 10 characters read
// after that the mark is lost
r.mark(10);
// do some reading
// jump back to the mark
r.reset();
}
Note that, BufferedReader supports marking but not all Readers do. You can use markSupported() to check.

How do I use BufferedReader to read lines from a txt file into an array

I know how to read in lines with Scanner, but how do I use a BufferedReader? I want to be able to read lines into an array. I am able to use the hasNext() function with a Scanner but not a BufferedReader, that is the only thing I don't know how to do. How do I check when the end of the file text has been reached?
BufferedReader reader = new BufferedReader(new FileReader("weblog.txt"));
String[] fileRead = new String[2990];
int count = 0;
while (fileRead[count] != null) {
fileRead[count] = reader.readLine();
count++;
}
readLine() returns null after reaching EOF.
Just
do {
fileRead[count] = reader.readLine();
count++;
} while (fileRead[count-1]) != null);
Of course this piece of code is not the recommended way of reading the file, but shows how it might be done if you want to do it exactly the way you attempted to ( some predefined size array, counter etc. )
The documentation states that readLine() returns null if the end of the stream is reached.
The usual idiom is to update the variable that holds the current line in the while condition and check if it's not null:
String currentLine;
while((currentLine = reader.readLine()) != null) {
//do something with line
}
As an aside, you might not know in advance the number of lines you will read, so I suggest you use a list instead of an array.
If you plan to read all the file's content, you can use Files.readAllLines instead:
//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);
using readLine(), try-with-resources and Vector
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\weblog.txt")))
{
String line;
Vector<String> fileRead = new Vector<String>();
while ((line = bufferedReader.readLine()) != null) {
fileRead.add(line);
}
} catch (IOException exception) {
exception.printStackTrace();
}

ReadLine - execute twice?

I need to be able to read each line of the file for multiple arguments, hence the for loop. After the first one, it does not seem to be reading them anymore, seems to skip the try statement. Any ideas? I'm sure Its something silly I am missing but have been playing about with it and unfortunately time is not on my side.
for (int j = 0; j < ags.length; j++){
try{
String nameFromFile = null;
BufferedReader InputReader = new BufferedReader(new InputStreamReader(System.in));
while ((nameFromFile = InputReader.readLine()) != null) {
// Do stuff
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You appear to have two sources you want to compare System.in and args I suggest you read these individually and then compare them.
Set<String> fromInt = new HashSet<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
for(String line; (line = br.readLine()) != null;)
fromIn.add(normalise(line));
}
// compare argsList with fromIn.
e.g.
for(String arg: args) {
if (fromIn.contains(normalise(arg))) {
// something
} else {
// something else
}
}
I need to be able to read each line of the file
What file? You're reading from System.in:
BufferedReader InputReader = new BufferedReader(new InputStreamReader(System.in));
Your code will block at this line until you enter something at the console.
You do not read a file, bu the System.in stream.
Every stream has an internal pointer, so the stream nows, which line was read at last.
If the System stream was read once, the pointer is pointing to the end of the stream.
As long as the stream is not reset, the read command will not return anything.
try
InputStream.reset()
or even better, only read the Stream once and cache the result! This is faster and safe, because the Stream input can change during iteration.
Your code will never exit from while loop.
while ((nameFromFile = InputReader.readLine()) != null)
In above loop it will print only one time and at the end of the file it will not be out of the while loop . That's why you are getting only one time output. Since it is not exited from while loop it does not go back into for loop. readLine() return the string and it is terminated by "\n" or "\r\n". Change as below and you will be able to read as ags.length
while ((nameFromFile = InputReader.readLine())=="\n")

Java - Reading From FIle

I am trying to read some lines from a file in Java. I have 4 lines in the file, but the problem is that it reads only 2 of the lines. Here's the code:
BufferedReader flux_in = new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
String line;
while (flux_in.readLine() != null)
{
line = flux_in.readLine();
System.out.println(line);
}
It is because you are calling readLine twice as often as you should.
Your first call inside the the while condition just threw the line away.
BufferedReader flux_in = new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
String line;
while ((line = flux_in.readLine()) != null)
{
System.out.println(line);
}
It does read all of them, although not quite in the way you'd like.
BufferedReader flux_in = new BufferedReader(new InputStreamReader(new FileInputStream("abc.txt")));
String line;
while (flux_in.readLine()!=null) //one line is read here
{
line = flux_in.readLine(); //the next one here
System.out.println(line);
}
In your code, the call in the loop test consumes a line, and then the call n the loop body consumes another line. So it would only print every other line.
String s = null;
while ((s = flux_in.readLine()) != null)
{
System.out.println(s);
}
BufferedReader is stateful and remembers what has been read from the file already. Every call of readLine() moves the cursor to the next line. You are calling readLine() twice per line: in the while loop and in the line assignment. Try this instead:
String line = flux_in.readLine();
while (line != null) {
System.out.println(line);
line = flux_in.readLine();
}
You're reading the line twice (in the while condition and in the while loop, so it's displaying one and then skipping the next. Change your code to this:
try {
BufferedReader flux_in = new BufferedReader(new FileReader("abc.txt"));
String line;
while ((line = flux_in.readLine()) != null)
System.out.println(line);
} catch(Exception e) { System.out.println("Error"); }

Categories

Resources