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() ) ) );
Related
I have to take name and address of user from user and put it into textfile. I write following code:
package selfTest.nameAndAddress;
import com.intellij.codeInsight.template.postfix.templates.SoutPostfixTemplate;
import java.io.*;
import java.util.Arrays;
/**
* Created by
*/
public class Test {
public static void main(String[] args) throws IOException {
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
//creating addressbook text file
File fl=new File("E:/addressbook.txt");
fl.createNewFile();
FileReader fr=new FileReader(fl);
BufferedReader in=new BufferedReader(fr);
boolean eof=false;
int inChar=0;
String[] name=new String[2];
String[] address=new String[2];
int counter=0;
do{
FileWriter fw=new FileWriter(fl);
BufferedWriter out=new BufferedWriter(fw);
System.out.println("Enter "+(counter+1)+" students name "+" and address");
name[counter]=br.readLine();
address[counter]=br.readLine();
out.write(name[counter]);
System.out.println("Nmae: "+name[counter]+" ddress: "+address[counter]);
counter++;
}while(counter<2);
}
}
When I run the code, it takes input from user but the text file is empty. The address and name is not written into text file. How can I store the name and address into text file in the above code.
You create the BufferedWriter, but never flush or close it.
These operations are what actually write to the file
As #ManoDestra pointed out in the comments, Java supports the try-with-resources statement, which allows you to format your statements like:
try(BufferedWriter out = new BufferedWriter(new FileWriter(fl))) {
Since BufferedWriter implements the AutoCloseable interface, Java will automatically take care of cleanup of out when the try block exits
A simpler alternative to BufferedWriter is PrintStream:
PrintStream printer = new PrintStream(new File("filepath"));
System.setOut(printer);
And then you can print whatever you want to the file, e.g.
printer.println(name[counter]);
And then close it at the end:
printer.close();
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());
}
I was wondering why I get a java.io.IOException: Stream closederror when using
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
In 2 different classes.
The setup is as follows.
public class SomeClass{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//br.readSomeStuff
br.close();
new SomeOtherClass(); //defo not passing the br along to the new class!
}
public class SomeOtherClass{
public SomeOtherClass(){
method():
}
private void method(){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
br.readLine();
// results into an IOEXCEPTION Stream close
}
}
The issue is gone when I close the BufferedReader in the first class AFTER the creation of the other class. I dont understand why this would give issues though. I am creating a new BufferedReader on System.in, why could this possibly result into a stream closed error?
Similar question here. Does not explain WHY System.in is closed for some reason though.
Thanks in advance!
Because when you close the BufferedReader all the underlying streams are closed. THis is the case with all the classes that wrap and read/write from/to streams.
This is a convenience so that you don't need to go through the entire set of objects you've instantiated (the InputStream, the InputStreamReader and finally the BufferedReader) and close all of them.
A simple test will demonstrate this:
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.close();
// Will throw IOException
int i = System.in.read();
}
System.in isn't special; it's an InputStream. The same thing would happen if the underlying stream was say, a FileInputStream rather than stdin:
public static void main(String[] args) throws IOException
{
File f = new File("SomeFileName");
FileInputStream fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
br.close();
// throw IOException
int i = fis.read();
}
Given that usually these constructors are chained (as they are in your example), it would be annoyingly cumbersome to have to retain and close each one.
Imagine having to do the following every time you wanted to use streams:
public static void main(String[] args) throws IOException
{
File f = new File("SomeFileName");
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(irs);
// Use the BufferedReader
br.close();
isr.close();
fis.close();
}
Intro java class tard here. I'm trying to read data from a file and then manipulate to a different file and save it. I think i'm close but having issues using scanner and .IO together. Any help would be great.
import java.util.Scanner;
import java.io.*;
public class fileswitch
{
public static void main(String[] Args) throws IOException
{
String filename;
String filename2;
String text;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);
System.out.print("Enter the name of a second file: ");
filename2 = keyboard.nextLine();
PrintWriter outputFile2 = new PrintWriter(filename2);
while (filename.hasNextLine())
{
text = filename.readAllLines();
text = text.toUpperCase();
outputFile2.print(text);
outputFile2.close();
}
}
}
You can also use for creating a new file
package test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class WriteStringToFile {
public static void main(String[] args) throws IOException {
String string = "This is\na test";
File file = new File("test.txt");
FileUtils.writeStringToFile(file, string);
}
}
And that is a good practice because you do not have to close streams.
This generates the test.txt file with the expected output
Try using BufferedReader
BufferedReader pw = new BufferedReader(new FileReader(fileName));
String s = null;
s = pw.readLine();
Working example
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
String filePath = keyboard.next();
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line = bufferedReader.readLine();
System.out.println(line);
}
Enter path on console as
C:\Users\path\Desktop\1.txt
You can use PrintWriter to write
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName2)));
Your code does not compile.
while (filename.hasNextLine()) // String#hasNextLine() does not exist
hasNextLine() belongs to Scanner which isn't being used for reading the file but just your console keystrokes from the keyboard.
If you meant to use outputFile there; that won't work either because you can't use a PrintWriter as a file reader. Well, the name kind of makes that obvious. Doesn't it?
But, you should avoid using PrintWriter for writing as well unless you're formatting the output. For plain character output prefer a FileWriter (enclosed within a BufferedWriter for performance). Similarly, for reading the files prefer a FileReader (enclosed within a BufferedReader again).
Here's how your code would look:
public static void main(String[] Args) throws IOException
{
// create the scanner for console
Scanner keyboard = new Scanner(System.in);
// read the input/output file names
System.out.print("Enter the name of a file: ");
String inFile = keyboard.nextLine();
System.out.print("Enter the name of a second file: ");
String outFile = keyboard.nextLine();
// close the scanner
keyboard.close();
// open file streams
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
// copy the data (line by line)
String text = null;
while ((text = reader.readLine()) != null)
{
writer.write(text);
writer.newLine();
}
// close the file streams
reader.close();
writer.close();
}
I have a file in .gz format. The java class for reading this file is GZIPInputStream.
However, this class doesn't extend the BufferedReader class of java. As a result, I am not able to read the file line by line. I need something like this
reader = new MyGZInputStream( some constructor of GZInputStream)
reader.readLine()...
I though of creating my class which extends the Reader or BufferedReader class of java and use GZIPInputStream as one of its variable.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.util.zip.GZIPInputStream;
public class MyGZFilReader extends Reader {
private GZIPInputStream gzipInputStream = null;
char[] buf = new char[1024];
#Override
public void close() throws IOException {
gzipInputStream.close();
}
public MyGZFilReader(String filename)
throws FileNotFoundException, IOException {
gzipInputStream = new GZIPInputStream(new FileInputStream(filename));
}
#Override
public int read(char[] cbuf, int off, int len) throws IOException {
// TODO Auto-generated method stub
return gzipInputStream.read((byte[])buf, off, len);
}
}
But, this doesn't work when I use
BufferedReader in = new BufferedReader(
new MyGZFilReader("F:/gawiki-20090614-stub-meta-history.xml.gz"));
System.out.println(in.readLine());
Can someone advice how to proceed ..
The basic setup of decorators is like this:
InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);
The key issue in this snippet is the value of encoding. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.
For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.
Most network protocols use a header or other metadata to explicitly note the character encoding.
In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.
Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!
GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();
BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));
String content;
while ((content = in.readLine()) != null)
System.out.println(content);
You can use the following method in a util class, and use it whenever necessary...
public static List<String> readLinesFromGZ(String filePath) {
List<String> lines = new ArrayList<>();
File file = new File(filePath);
try (GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));) {
String line = null;
while ((line = br.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
} catch (IOException e) {
e.printStackTrace(System.err);
}
return lines;
}
here is with one line
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream(
"F:/gawiki-20090614-stub-meta-history.xml.gz")))))
{br.readLine();}