read method for jTextArea makes BufferedReader null - java

I'm trying to use read method for jTextArea from BufferedReader. It works and my text appears in jTextArea successfully. but after using read method it makes BufferedReader null. Here is my example code:
private void Calculate() throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file)) ;
jTextArea.read(br, "jTextArea");
System.out.println(br.readLine());
}
When I comment out this "jTextArea.read(br, "jTextArea");" println works properly and prints out the first line. But in normal case It prints null.
P.S: "file" is my instance variable. There is no problem with this variable, it works properly too.

BufferedReader br object has reached its end after being read. So, not the br is null, but it's current line, which you're trying to read by br.readLine(). Otherwise a NullPointerException would be thrown on calling br.readLine().
You need to reinitialize BufferedReader and got the first line printed:
private void Calculate() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
jTextArea.read(br, "jTextArea");
br = new BufferedReader(new FileReader(file));
System.out.println(br.readLine());
}

Related

how to recover BufferedReader object from ByeArrayOutputStream

I have written a code to stub the System.out.println and passing the object of BuffredReader into it.
My question is how to recover the BufferedReader object?
import java.io.*;
class Test {
public static void main(String args[]) throws IOException {
// stubbing the default print statement
ByteArrayOutputStream outcontent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outcontent);
//createing a BufferedReader obj and passing to print
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(br);
//trying to get the value from the outcontent and
// but i need to serialise this to BufferedReader
System.err.println(outContent.toString());
}
}
I have tried to use this answer but i am getting the error java.io.StreamCorruptedException: invalid stream header: 6A617661
Since you already have a ByteArrayOutputStream, you should try something like this:
BufferedReader reader = new BuffererdBeader( new InputStreamReader(
new ByteArrayInputStream( outcontent.toByteArray() ) ) );

BufferedReader reader.readLine() returns null [duplicate]

I am currently trying to read a String from a BufferedReader but cant find a way to do this...
Of course I tried
BufferedReader inStream = null;
inStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
String test = inStream.readLine();
However the result turns out as null when trying to print to a screen even though the BufferedReader inStream is equal to some kind of message.
Based on the documentation, the BufferedReader.readLine() returns null only when the end of the stream is reached. This means if the first call to readLine() returns null, there was nothing in the input stream to begin with.

BufferedReader then write to txt file?

Is it possible to use BufferedReader to read from a text file, and then while buffered reader is reading, at the same time it also storing the lines it read to another txt file using PrintWriter?
If you use Java 7 and want to copy one file directly into another, it is as simple as:
final Path src = Paths.get(...);
final Path dst = Paths.get(...);
Files.copy(src, dst);
If you want to read line by line and write again, grab src and dst the same way as above, then do:
final BufferedReader reader;
final BufferedWriter writer;
String line;
try (
reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
doSomethingWith(line);
writer.write(line);
// must do this: .readLine() will have stripped line endings
writer.newLine();
}
}
To directly answer your question:
you can, and you can also use BufferedWriter to do so.
BufferedReader br = new BufferedReader(new FileReader(new File("Filepath")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Filepath")));
String l;
while((l=br.readLine())!=null){
... do stuff ...
bw.write("what you did");
}
bw.close();
If you just need to copy without inspecting the data, then it's a one liner:
IOUtils.copy(reader, printWriter);
Yes. Open the BufferedReader, and then create a PrintWriter. You can read from the stream as you write to the writer.

Problem reading from file

so i'm trying to read from a file a number of lines, and after that put them in a String[]. but it doesn't seem to work. what have i done wrong?
String[] liniiFisier=new String[20];
int i=0;
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
liniiFisier[i]=strLine;
i++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
for(int j=0;j<i;j++)
System.out.println(liniiFisier[i]);
Change that last line to
System.out.println(liniiFisier[j]); // important: use j, not i
You should tell us what's happening and what problem occurred.
But I yet see some errors:
Imagine your file has more than 20 lines, so you'll try to access liniiFisier[20], but this field is not present! Results in ArrayIndexOutOfBounds
In your for loop you are iterating j but always using i...
Creating the BufferedReader can be done in less code:
FileReader fr = new FileReader ("textfile.txt");
BufferedReader br = new BufferedReader (fr);
Since I don't know about your particular problem this might not solve it, so please provide more information ;-)

Closing nested Reader

When reading from a text file, one typically creates a FileReader and then nests that in a BufferedReader. Which of the two readers should I close when I'm done reading? Does it matter?
FileReader fr = null;
BufferedReader br = null;
try
{
fr = new FileReader(fileName);
br = new BufferedReader(fr);
// ...
}
finally
{
// should I close fr or br here?
}
I'm a little paranoid when it comes to exception-safety. What happens when the BufferedReader constructor throws an exception? Does it close the nested reader? Or is it guaranteed not to throw?
Generally, close() on the outermost stream wrapper will call close() on the wrapped streams. However, if you think it's likely that a constructor will throw an exception, make liberal use of the Closeable interface.
FileReader fr = new FileReader(fileName);
Closeable res = fr;
try {
BufferedReader br = new BufferedReader(fr);
res = br;
} finally {
res.close();
}
So, even if the JVM ran out of heap space for the buffer and threw an error, you wouldn't leak a file handle.
For Java 7 and above use try-with-resources:
try (FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr)) {
// do work
}
Closing only the BufferedReader is enough, cause it wraps the FileReader. If you look at the source code of BufferedReader you will see that the close method, closes the wrapped stream.
Close the BufferedReader in a finally block.
If you call the BufferedReader's close method, the BufferedReader will call the FileReader's close method. Thus both close method's are called. More precisely the BufferedReader will do nothing BUT calling the FileReader's close method. Thus it does not matter at all. Though I think it is good practice too call the BufferedReader's close method.
Nothing is guaranteed not to throw. Because the buffer is allocated it may throw OutOfMemoryError. I usually separate my code into 2 sections: acquire resources and then use resources. Each section usually has unique cleanup needs
Here is the code to illustrate:
// Acquire resources section.
final FileReader fr = new FileReader( fileName );
BufferedReader br = null;
try
{
br = new BufferedReader(fr);
}
finally
{
if ( br == null )
{
// Note that you are closing the fr here
fr.close( );
}
}
// Use resources section
try
{
// ... use br
}
finally
{
// Now that br is safely constructed, just all its close
br.close( );
}
And I agree with you, there is nothing worth than silently loose a file handler in the long running server application.

Categories