wrong Reading with BufferedReader - java

I have problem with reading data from file.
In each line (except first) first char is lost!
Maybe i have troubles with coding, but i try to set UTF-8, UniCode, ANSI, and result is fast the same...
Code:
try (FileReader fr = new FileReader("123.txt")) {
// create a buffer for file reader
BufferedReader br = new BufferedReader(fr);
do {
input = br.readLine();
System.out.println(input);
} while (br.read() != -1);
} catch (IOException ex) {
System.out.println("IOex : " + ex);
}
Console:
2
FFFFFF
FAF9F5
FDBCA1
FBCCB8
but must be:
2
#FFFFFF
2
#FAF9F5
6
#FDBCA1
9
#FBCCB8
9
it only works, when i put slashes before lines.
2
\#FFFFFF
\2
\#FAF9F5
\6
\#FDBCA1
\9
\#FBCCB8
\9
What can it be?
Thanks!

The problem is with the end of your do loop:
do {
input = br.readLine();
if (input.endsWith("\n")) {
input = input.substring(0, input.indexOf("\n"));
}
System.out.println(input);
} while (br.read() != -1);
You're calling read() which will read the first character of the next line - but you're only using that to check for whether the file has ended. (Notice how you've got the first character of the first line, because there you're calling readLine without previously calling read.)
This would work fine - and be simpler:
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
readLine returns null when you've reached the end of the data. Note that you don't need to check for input containing \n as you're already reading one line at a time, and \n is deemed to be a line separator.

Related

Array is getting index out of bounds in one specific spot of text file

So I have a text file with very simple text. Each line is simply make,model,vin#. I have about 3 or 4 lines to test. When I print out these lines, only the lines with even indexes get printed. If I don't include the else statement then it gives an out of bounds exception. So for example, with text file input as shown
Hi guys. I have a text file that is only a few lines long. On each line, it is formatted as such:make,model,number. When I run my program, it prints the lines normally until it gets to the third line of the text file(there's only 5 lines). This third line is where I get the index out of bounds exception.
public CarDealershipSystem(File carFile, File associateFile) {
try (BufferedReader br = new BufferedReader(new FileReader(carFile))) {
String line;
for(;;) {
line = br.readLine();
String[] lineArray = line.split(",");
System.out.println(lineArray[0]);
System.out.println(lineArray[1]);
System.out.println(lineArray[2]);
}
}catch(IOException e) {
e.getLocalizedMessage();
e.printStackTrace();
}
You have "line = br.readLine()" in two places in "while" cycle and in "if" block that causes two calls to readLine per cycle. Besides this block is pointless because the "while" condition already handles it.
tldr: remove
if((line = br.readLine()) == null) {
break;
}
you need a break when you reach the end of the file.
String line;
while((line = br.readLine()) != null) { //stop loop when line == null
line = br.readLine();
}
you need to check your input, before split
String[] lineArray = line.split(",");
if (lineArray != null && lineArray.length == 3) { //will help you avoid the ArrayIndexOutOfBoundsException exception
System.out.println(lineArray[0]);
System.out.println(lineArray[1]);
System.out.println(lineArray[2]);
}

How to move the first element of each line to the end of that line in text files?

I have a text file trying to move the first element of the line to the end of line in Java
4, 2,-2,2,0,2,-2,-2,2,2,-2
5,-2,-2,0,0,0,-2,-2,-2,0,-2
6, 2,-2,2,0,2,-2,-2,2,2,-2
5,-2,-2,0,0,0,-2,-2,-2,0,-2
7, 2,-2,2,0,2,-2,-2,2,2,-2
5,-2,-2,0,0,0,-2,-2,-2,0,-2
I need to move the first number to the end of the line. For example:
2,-2,2,0,2,-2,-2,2,2,-2,4
-2,-2,0,0,0,-2,-2,-2,0,-2,5
2,-2,2,0,2,-2,-2,2,2,-2,6
-2,-2,0,0,0,-2,-2,-2,0,-2,5
2,-2,2,0,2,-2,-2,2,2,-2,7
-2,-2,0,0,0,-2,-2,-2,0,-2,5
Any help please
Here is a simple working script:
try (BufferedReader br = Files.newBufferedReader(Paths.get("input.txt"));
FileWriter writer = new FileWriter("output.txt");
BufferedWriter bw = new BufferedWriter(writer)) {
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("([^,]+),(.*)", "$2,$1\r\n");
bw.write(line);
}
}
catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
The "secret sauce" in this otherwise boilerplate code is the following regex string replacement:
line = line.replaceAll("([^,]+),(.*)", "$2,$1\r\n");
This matches and captures the very first term in one capture group, along with everything which follows the first comma in a second capture group. Then it replaces with $2,$1 to effectively move the first CSV term to the end of the line.

Bufferedreader doesn't read the whole line at a time?

I'm using BufferedReader to read a text file line by line using Bufferedreader.readLine() but suddenly it doesn't read the whole line instead it reads only the first string only
Example: if the first line in the text file is:
[98.0,20.0,-65.0] [103.0,20.0,-70.0] 5.0 [98.0,20.0,-70.0] ccw
And my code is:
BufferedReader br = new BufferedReader(new FileReader("path" + "arcs.txt"));
String Line = br.readLine();
System.out.println(Line):
The output will be:
[98.0,20.0,-65.0]
Why is this happening?
The readLine() method of the buffer reader reads a string until it reaches a line seperator such as \n or \r. Your textfile must have these tokens after [98.0,20.0,-65.0].
The BufferedReader works internally as follows:
The InputSream or InputFile character stream will be buffered until an instance of \n (linefeed) or \r (carriage return) occures. Without the occurence of one of these two characters the BufferedReader is stuck in a while loop. An Exception to this case is, when the input character stream is closed. Therefore the only reasonable explanation why it's returning early must be, that there is some kind of line ending character after the first bit of the line. To make sure you catch everything in the file you can add a surrounding while loop.
Example:
// Please ignore the fact that I am using the System.in stream in this example.
try(BufferedReader br = new BufferedReader( new InputStreamReader( System.in) ))
{
String line;
StringBuilder sb = new StringBuilder();
// Read lines until null (EoF / End of File / End of Stream)
while((line = br.readLine()) != null)
{
// append the line we just read to the StringBuilds buffer
sb.append(line);
}
// Print the StringBuilders buffer as String.
System.out.println(sb.toString());
}
catch ( IOException e )
{
e.printStackTrace();
// Exception handling in general...
}

Null in standard input in Java

I am working on small program where user inputs text in standard input and then this text is returned with proper alignment.
My main block of code where input is being read line by line:
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
for (String nextLine, line = br.readLine(); line != null; line = nextLine) {
nextLine = br.readLine();
// Work with "line"
}
}
catch (IOException ex) {
System.exit(-1);
}
}
But input is never read all. Always last line is missing and line is never null. After little debugging I found out that br.readLine() on line nextLine = br.readLine(); doesn't return anything (literally it doesn't return anything. No exception is thrown though.) and program keeps running but is not executing any other lines of my code. I also tried reading from file and this problem doesn't occur.
That is probably because readLine() blocks until a new line is available or the stream reaches EOF (which never happens when you read from System.in).
You never get the last input because your loop always processes the previously read line.
Try this:
for (String line; (line = br.readLine()) != null;)
and break from this loop when you've read all the input you need, ex:
if(line.equals("finish")){
break;
}
When your input comes from standard input, you have to let your program know when the input ends. Otherwise it will keep waiting for the next input to be entered.
Therefore you should decide on some character or String that would mark the end of the input.
For example, here typing done would end the loop :
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
for (String nextLine, line = br.readLine(); line != null && !line.equals("done"); line = nextLine) {
nextLine = br.readLine();
// Work with "line"
}
}
catch (IOException ex) {
System.exit(-1);
}
}

Trying to read this file in parts. read some part and skip some

I am trying to read a file, I want to read some part of the file and skip some part untill I get to the end of the file. This is what I have but I am not getting my desired result. The idea is to read through all the lines and check if it starts with either "CH" or "CL" if not move to the next line until the end of file and store all those that match the criteria
new BufferedReader (new FileReader ("c:\\demo5.properties\\"));
while(( br.readLine()) != null ){
if (br.readLine().startsWith("CH") || br.readLine().startsWith("CL")) {
buf = new StringBuffer();
buf.append( br.readLine());
while (br.readLine()!= null && !br.readLine().startsWith("#") && !br.readLine().contains("claimID")){
buf.append( br.readLine()).append( "\n" );
}
z = buf.toString();
System.out.println(z);
s3+= z;
}
br.readLine();
FILE FORMAT
CH.field
CH.field
CH.field
CH.field
CH.field
#CH.field
#CH.field
#CH.field
#CH.field
*********
**
*********
CL1.field
CL1.field
CL1.field
CL1.field
CL1.field
*****************
#Result.CL1.field
#Result.CL1.field
#Result.CL1.field
Result.CL1.field
*********
CL4.field
CL4.field
CL4.field
#CL4.field
#CL4.field
#CL4.field
***********
#Result.CL4
#Result.CL4
#Result.CL4
#Result.CL
Result.CL4
CL5.field
CL5.field
CL5.field
#CL5.field
#CL5.field
OUTPUT
CH.fieldCH.field
CL1.field#Result.CL1.field
CL4.field
CL4.field
#CL4.field
CL5.fieldCL5.field
Look at this loop:
while (br.readLine()!= null
&& !br.readLine().startsWith("#")
&& !br.readLine().contains("CH.field.claimID")){
buf.append( br.readLine()).append( "\n" );
}
You're calling readLine() 4 times. That's going to read four different lines. You want something like:
String line;
while ((line = br.readLine()) != null &&
!line.startsWith('#') &&
!line.contains("CH.field.claimID")) {
buf.append(line).append("\n");
}
At least, I think that's what you want - I'm finding the description a little confusing. Anyway, that will read each line, stop when it reaches either the end of a file or a line starting with "#" or a line containing "CH.field.claimID"... but build up a StringBuffer containing all the lines before that point.
A call to readLine() will read one line that ends with a '\n' and then file pointer will point to next line (or it'll point to whatever after '\n' to be more precise).
for e.g.
Before readLine():
filePointer --> This is first line \n
----------------- This is second line \n
After readLine():
------------------This is first line \n
filePointer --> This is second line \n
You are calling readLine() multiple times thinking that it refers to same line. Which is where you are going wrong.
From your question I gathered that you want to store all lines that begin with "CH" or "CL" and ignore the rest.
All the br.readline calls are moving that file reader pointer to the next line.
The formatting looks odd to me, maybe try this:
String input = "";
buf = new StringBuffer();
new BufferedReader (new FileReader ("c:\\demo\\TestIL_Cross_000005.properties\\"));
// read in the line to "input" if it exists
while((input = br.readLine()) != null ){
// check for starting string match
if (input.startsWith("CH") || input.startsWith("CL")) {
// append to whatever data struct here since it matches
buf.append(input + "\n");
// print "input" here for testing
}
}
This is a very basic mistake that you have made in your code. You must store the data returned by readLine() method in a String variable, and use it for further operations. You are calling the readLine() method every time, you want to perform operation on the received String, as a result it every time fetches new data and previous data is lost.
Modified version of your code :
new BufferedReader (new FileReader ("c:\\demo\\TestIL_Cross_000005.properties\\"));
String line = null;
while(( line= br.readLine()) != null ){
if (line.startsWith("CH") || v.startsWith("CL")) {
buf = new StringBuffer();
buf.append(line);
while (line!= null && !line.startsWith("#") && !line.contains("CH.field.claimID")){
buf.append( line).append( "\n" );
}
z = buf.toString();
System.out.println(z);
s3+= z;
}
}
Here I have just collected the data from readLine() method in a String reference, and used in for performing different checks.

Categories

Resources