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...
}
Related
I found this code from another question
private void updateLine(String toUpdate, String updated) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(data));
String line;
String input = "";
while ((line = file.readLine()) != null)
input += line + "\n";
input = input.replace(toUpdate, updated);
FileOutputStream os = new FileOutputStream(data);
os.write(input.getBytes());
file.close();
os.close();
}
This is my file before I replace some lines
example1
example2
example3
But when I replace a line, the file now looks like this
example1example2example3
Which makes it impossible to read the file when there are a lot of lines in it.
How would I go about editing the code above to make my file look what it looked like at the start?
Use System.lineSeparator() instead of \n.
while ((line = file.readLine()) != null)
input += line + System.lineSeparator();
The issue is that on Unix systems, the line separator is \n while on Windows systems, it's \r\n.
In Java versions older then Java 7, you would have to use System.getProperty("line.separator") instead.
As pointed out in the comments, if you have concerns about memory usage, it would be wise to not store the entire output in a variable, but write it out line-by-line in the loop that you're using to process the input.
If you read and modify line by line this has the advantage, that you dont need to fit the whole file in memory. Not sure if this is possible in your case, but it is generally a good thing to aim for streaming. In your case this would in addition remove the need for concatenate the string and you don't need to select a line terminator, because you can write each single transformed line with println(). It requires to write to a different file, which is generally a good thing as it is crash safe. You would lose data if you rewrite a file and get aborted.
private void updateLine(String toUpdate, String updated) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(data));
PrintWriter writer = new PrintWriter(new File(data+".out"), "UTF-8");
String line;
while ((line = file.readLine()) != null)
{
line = line.replace(toUpdate, updated);
writer.println(line);
}
file.close();
if (writer.checkError())
throw new IOException("cannot write");
writer.close();
}
In this case, it assumes that you need to do the replace only on complete lines, not multiple lines. I also added an explicit encoding and use a writer, as you have a string to output.
This is because you use OutputStream which is better for handling binary data. Try using PrintWriter and don't add any line terminator at the end of the lines. Example is here
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.
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
Sorry in advance if the title is misleading/wrong but this is the best I can do after a really long day spent practicing with Java. (my brain is melting)
I put this code togheter to read a file and copy it into another file, skipping the line/lines that begins with a given string (BeginOfTheLineToRemove). It actually works and remove the desired line, but, for some reason, it forgets about the \n (newline). Spacing and symbols are copied. I can't figure it out. I really hope someone will help. cheers from a java newb from italy ;)
public void Remover(String file, String BeginOfTheLineToRemove) {
File StartingFile = new File(file);
File EndingFile = new File(StartingFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(EndingFile));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith(LineToRemoveThatBeginWithThis)) {
continue;
}
pw.write(line);
}
pw.close();
br.close();
}
Use pw.println instead of pw.write. println adds new line character after it writes content.
You are using PrintWriter.write() to write the lines - This does not by default write newline at the end. Use println() instead.
This will probably help you.
The BufferedReader.readLine() method does not read any line termination characters. So therefore your line will not contain any termination characters.
BufferedReader#readLine documentation says:
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
That is, the reader strips the line termination characters from your Strings, so you need to manually add them again:
// \n on Linux/Mac, \r\n on Windows
String lineSep = System.getProperty("line.separator");
pw.write(line);
pw.write(lineSep);
BufferedReader.readLine() uses the newline to identify the end of the line, and the string that it returns does not contain this newline. The newline is a separator, so it is not considered part of the data.
To compensate for this, you can add a newline to your output, like so:
while((line = br.readLine()) != null) {
if(line.startsWith(LineToRemoveThatBeginWithThis)) continue;
pw.write(line);
pw.println();
}
The extra call to PrintWriter.println() will print a newline after you write out your line of text.
Outside the loop get the system's line seperator:
String lineSeparator = System.getProperty("line.separator");
Then append that to the line you've read in:
pw.write(line+lineSeparator);
I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example.
For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\n) character and then incerement a line variable that i created:
FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;
int lines = 1;
while ((strLine = buffRead.readLine()) != null)
{
if(strLine.contains(newLines))
{
System.out.println("Line Found");
lines++;
}
}
System.out.println("Total Number Of Lines In File: " + lines);
This does not work for, it simply display 0 at the end of this file. I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file.
Would anyone happen to know the reason why the above code does not work?
Read the javadocs for 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
readLine() strips newlines. Just increment every iteration of the loop. Also, you're overcomplicating your file reading code. Just do new BufferedReader(new FileReader("src/file.txt"))