Java IOException - Stream Closed - java

I get "IOException: Stream Closed" when I run this program. The text contains many lines of data. Program should read each line, do necessary function and write the output to a new file. I am confused as to which writer should be closed first and where.
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
try {
// change this value
FileInputStream fis = new FileInputStream("C:\\Users\\Rao\\Desktop\\test.txt");
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
processLine(sCurrentLine); //error
}
} finally {
if (br != null)
br.close();
}
}
public static void processLine(String line) throws IOException {
String prename = line.substring(22);
int siz= prename.indexOf(":");
String name = prename.substring(0, siz);
URL oracle = new URL("http://ip-api.com/json/"+name);
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) // error
// System.out.println(inputLine);
in.close();
String baby = (line + "\t" + inputLine);
try {
FileWriter writer = new FileWriter("C:\\Users\\Rao\\Desktop\\output.txt", true);
writer.write(baby);
writer.write("\r\n"); // write new line
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The exception is as follows:
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at URLReader.processLine(URLReader.java:31)
at URLReader.main(URLReader.java:13)

You close the input stream in your loop:
while ((inputLine = in.readLine()) != null) // error
// System.out.println(inputLine);
in.close();
You should close the stream outside of the loop:
while ((inputLine = in.readLine()) != null) // error
{
//dosomething
// System.out.println(inputLine);
}
in.close();

You should put a function call in the while loop, like:
a System.out.println("Hi, I'm a row!"); or
uncomment System.out.println(inputLine); or
put a semicolon at the end of the while statement
in order to let it to execute properly.
The code as it is written executes (comments omitted):
...
while ((inputLine = in.readLine()) != null)
in.close();
...
so the first cycle of the loop executes correctly and runs in.close(). Then the second cycle the call inputLine = in.readLine() fails because the stream is closed and then the exception is thrown.

Related

NullPointerException reading line from file [duplicate]

This question already has answers here:
Java if/else behaving strangely
(4 answers)
Closed 7 years ago.
I have this code:
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("hello.txt"));
String line;
while ((line = br.readLine().trim()) != null) {
if (line.startsWith("Hello")) {
line = br.readLine().trim();
} else {
... code ...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But once the file reaches the end, I get this error:
Exception in thread "main" java.lang.NullPointerException
On the line:
while ((line = br.readLine().trim()) != null) {
Why? How to fix it?
Try the following; ine which you are trying to read is null hence calling trim throws NPE;
while (br.readLine() != null)
{
line = br.readLine().trim()
}
while ((line = br.readLine().trim()) != null)
remove the trim()
and added it within the while loop.
line = line.trim();
When you try to read using readLine()
line = br.readLine().trim())
if br.readLine() return null, then calling trim() cause NPE.
while ((line = br.readLine()) != null) {
line.trim();
if (line.startsWith("Hello")) {
if ((line = br.readLine()) != null) {
line.trim();
}
} else {
}
}

PrintWriter object doesn't print all the lines in text document to out put file

public String getText()
{
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[]{"spring-config-server.xml"});
Resource resource = appContext.getResource("file:D:\\text\\test.txt");
StringBuilder builder = new StringBuilder();
try{
InputStream is = resource.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
PrintWriter out=null;
while ((line = br.readLine()) != null) {
//System.out.println(line);
out = new PrintWriter(new FileWriter("D:\\outputfile.txt"));
out.println(line);
//br.close();
}
out.close();
br.close();
}catch(IOException e){
e.printStackTrace();
}
return builder.toString();
}
Create PrintWriter instance out of your while loop.
Move it outside the loop.Due to which new instance is created every line
out = new PrintWriter(new FileWriter("D:\\outputfile.txt"));
You are creating new PrintWriters in the loop. Make it outside of it.
out = new PrintWriter(new FileWriter("D:\\outputfile.txt"));
while ((line = br.readLine()) != null) {
//System.out.println(line);
out.println(line);
//br.close();
}
The PrintWriter is being assigned to a new instance during each loop iteration. Declare the PrintWriter outside of the loop.
String line;
PrintWriter out= new PrintWriter(new FileWriter("D:\\outputfile.txt"));
while ((line = br.readLine()) != null) {
out.println(line);
}

how to read last line in a text file using java [duplicate]

This question already has answers here:
Quickly read the last line of a text file?
(10 answers)
Closed 9 years ago.
I am making a log and I want to read the last line of the log.txt file, but I'm having trouble getting the BufferedReader to stop once the last line is read.
Here's my code:
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Here's a good solution. In your code, you could just create an auxiliary variable called lastLine and constantly reinitialize it to the current line like so:
String lastLine = "";
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
lastLine = sCurrentLine;
}
This snippet should work for you:
BufferedReader input = new BufferedReader(new FileReader(fileName));
String last, line;
while ((line = input.readLine()) != null) {
last = line;
}
//do something with last!

how to read line by line in android?

i am using this code.
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((br.readLine()) != null) {
temp1 = br.readLine();
temp2 = br.readLine();
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
but this is showing exception and is not updating temp1 and temp2.
The exception you see - that I would strongly recommend a) to catch as a specific type, e.g. IOException, and b) to log or show with a message or a stack trace, and c) at least to check for in LogCat, from the DDMS perspective if you are programming with Eclipse - is probably due to Android not finding the config.txt file you are trying to open. Usually, for the simplest cases such as yours, files that are private to an application are opened using openFileInput - see the documentation for details.
Apart from the exception, your reading loop is defective: you need to initialize an empty string before entering, and fill it in the while condition.
String line = "";
while ((line = br.readLine()) != null) {
// do something with the line you just read, e.g.
temp1 = line;
temp2 = line;
}
However, you don't need a loop if you just want to save the first two lines in different variables.
String line = "";
if ((line = br.readLine()) != null)
temp1 = line;
if ((line = br.readLine()) != null)
temp2 = line;
As others have already pointed out, calling readLine consumes a line, so if your config.txt file contains only one line your code consumes it on the while condition, then temp1 and temp2 get null assigned because there's no more text to read.
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
temp1 = line;
temp2 = line;
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
br.readLine() in while already consumes a line.
Try this
LineNumberReader reader = new LineNumberReader(new FileReader("config.txt")));
String line;
while ((line = reader.readLine()) != null) {
//doProcessLine
}
if you want to save the first two lines you have to do:
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = "";
if((line = br.readLine()) != null)
temp1 = line;
if((line = br.readLine()) != null)
temp2 = line;
}
catch(Exception e)
{
e.printStackTrace();
}

Fetch and store output from a subprocess in Java

I'm working on something that requires me to start to subprocess(command prompt) and execute some commands on it. I need to fetch the output from the subprocess and store it in a file or String.
here's what I have done so far, and it doesn't work:
public static void main(String args[])
{
try
{
Runtime RT = Runtime.getRuntime();
String command = "cmd /c start javap java.lang.String";
File file = new File("write.txt");
Writer output = new BufferedWriter(new FileWriter(file));
BufferedReader br = new(BufferedReader(newInputStreamReader(RT.exec(command).getInputStream()));
String temp = br.readLine();
while(!temp.equals(null))
{
output.write(temp);
temp = br.readLine();
}
output.close();
RT.exec("exit");
}
catch(Exception e)
{
System.out.println(e);
}
}
Start changing this:
new(BufferedReader(newInputStreamReader(
To:
new BufferedReader(new InputStreamReader(
Compile and see if you still have the problem
edit
Also, there is a good reason why you shouldn't catch Exception, you also catch programming errors like a NullPointerException
while( !temp.equals(null)) { //Throws NullPointerExceptin when temp is null
Change it with:
while( temp != null ) { //!temp.equals(null)) {
Finally you don't have to "exit" since you're not inside the cmd really.
Corrected version
This version runs as you intend:
import java.io.*;
class Rt {
public static void main(String args[]) throws Exception {
Runtime RT = Runtime.getRuntime();
String command = "javap java.lang.String" ;
File file = new File("write.txt");
Writer output = new BufferedWriter(new FileWriter(file));
BufferedReader br = new BufferedReader(new InputStreamReader(RT.exec(command).getInputStream()));
String temp = br.readLine();
while( temp != null ) { //!temp.equals(null)) {
output.write(temp);
temp = br.readLine();
}
output.close();
//RT.exec("exit");
}
}
edit
Final remarks:
Since Java 1.5 the preferred way to invoke a command is using ProcessBuilder and it is better if you use an array of strings instead of a single string ( or varargs ).
When you're building your output you can get rid of the file object and pass the file name directly to the filewriter.
While reading the line you can assign and evaluate in the condition.
Java's coding conventions suggest to use the opening brace in the same like.
This would be my version of your code:
class Rt {
public static void main(String args[]) throws Exception {
Writer output = new BufferedWriter(new FileWriter ( "write.txt"));
InputStream in = new ProcessBuilder("javap", "java.lang.String").start().getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(in));
String line = null;
while( ( line = br.readLine() ) != null ) {
output.write( line );
}
output.close();
}
}
It might need still some work, but I hope it helps you.
Here is an example which should work:
StringBuffer outStream = new StringBuffer();
StringBuffer errStream = new StringBuffer();
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec(command);
} catch (IOException ex) {
ex.printStackTrace();
return;
}
InputStream outIs = process.getInputStream();
MonitorOutputThread sout = new MonitorOutputThread(outIs, outStream);
sout.run();
InputStream errIs = process.getErrorStream();
MonitorOutputThread serr = new MonitorOutputThread(errIs, errStream);
serr.run();
while (sout.isAlive() || serr.isAlive()) {
try {
sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
// ignore
}
}
And the code for MonitorOutputThread
private class MonitorOutputThread extends Thread {
private final InputStream is;
private final StringBuffer output;
public MonitorOutputThread(InputStream is, StringBuffer output) {
this.is = is;
this.output = output;
}
#Override
public void run() {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
try {
while ((line = br.readLine()) != null) {
output.append(line);
output.append(LINE_SEPARATOR);
}
if (output.length() >= 1) {
char lastChar = output.charAt(output.length() - 1);
if (lastChar == '\n') {
output.deleteCharAt(output.length() - 1);
}
}
} catch (IOException ex) {
ex.printStackTrace();
return;
}
}
}
This should catch both the standard output and standard error of the command.
DevDaily has a simple example of how to work with Process class.
See the snippet:
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// run the Unix "ps -ef" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("ps -ef");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
or even check this code I've writen some time ago

Categories

Resources