BufferedReader stuck at last input line without ending the program - java

I'm using BufferedReader to read data from System.in (a text file redirected context: < file.txt) then write it to the console. The problem is my program shows all lines except the last one and still works without doing any thing. If I manually end it it will write the final line.
This is my code:
public void updateText() throws IOException {
try {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
System.out.println(inputLine);
}
inputStreamReader.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Here an alternative way of waiting on available data (Ref.: Java 11 - method BufferedReader.ready()):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class TestClass {
public static void main(String[] args) {
try (InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
// wait until data available
while (!bufferedReader.ready()){
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example output:
Hello world
Hello world
Hello world
Hello world

If this only occurs in Eclipse, your issue is most likely a duplicate and bug 513713.
You don't need to read standard input line by line when you could simply transfer the data in one step, replacing the body of updateText():
System.in.transferTo(System.out);

Related

Read URL in Java

My goal with this program is to extract a website's content and output it to console. However, an exception gets thrown every time I run this code. I am wondering what I am doing wrong, and if anyone can point me in the right direction. Thank you ahead of time!
public class twikiripper {
public static URL url;
public static void main(String[] args) {
BufferedReader br = null;
try{
URL url = new URL("http://www.google.com");
}catch(MalformedURLException ex){}
try {
url.openConnection();
br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb);
}catch(Exception e){
System.out.println("Exception: "+e.toString());
}
}
My code is above. I was wondering, why am I always outputting Exception: java.lang.NullPointerException ? I seem to always throw this exception. I thought I was doing everything right.
What I am trying to do is display the output code from a website, that is all. Please help !
You have an unnecessary try-catch block in your code. Try this:
public static void main(String[] args) {
BufferedReader br = null;
try {
URL url = new URL("http://www.google.com");
url.openConnection();
br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb);
}catch(Exception e){
System.out.println("Exception: "+e.toString());
}
}
And also make sure that your are importing the correct classes.
The reason for null pointer exception is:
In your code, in url.openConnection(); variable url is local and its scope ends at the end of the its try block.
Try this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class twikiripper {
public static URL url;
public static void main(String[] args) {
BufferedReader br = null;
try{
url = new URL("http://www.google.com"); // I have changed this line
}catch(MalformedURLException ex){}
try {
url.openConnection();
br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb);
}catch(Exception e){
System.out.println("Exception: "+e.toString());
}
}
}
In your first try block a the local variable hides the field url. You've got two different variables with the same name. Change URL url = new URL("http://www.google.com"); to url = new URL("http://www.google.com"); or follow NiVeRs answer. – Eritrean 8 mins ago
Correct! Thank you.
below code will fullfill your requirement --
package com.subham.testing;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class Test13 {
public static URL url;
public static void main(String[] args) {
BufferedReader br = null;
try {
url = new URL("http://www.google.com");
} catch (MalformedURLException ex) {
System.out.println("came exception");
}
try {
url.openConnection();
br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb);
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
}
}
You were creating new url object in first try block so in second try block was getting null as it was just decleared but not initialized.

Why isn't this reading from the specified file?

I'm working on a simple, model peer-to-peer networking system. The bootstrap server is supposed to serve a text file containing lists of IPs that connected to nodes to help each node discover more peers. However, it doesn't write the file like it should, and I don't understand why. Here's what I have so far:
package network;
import java.net.*;
import java.io.IOException;
import java.io.*;
import javax.swing.JOptionPane;
public class PeerBootstrapServer
{
public static void main(String[] args) throws IOException
{
String peerFilePath = JOptionPane.showInputDialog("Please provide a peer list path:");
File file = new File(peerFilePath);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
BufferedReader reader = new BufferedReader(new FileReader(file));
ServerSocket listener = new ServerSocket(8088);
try
{
while(true)
{
Socket socket = listener.accept();
try
{
String peer = socket.getInetAddress().getHostAddress();
boolean isRecognized = false;
for(String line; (line = reader.readLine()) != null; )
{
if(line == peer)
{
isRecognized = true;
}
}
if(isRecognized == false)
{
writer.newLine();
writer.write(peer);
}
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
for(String line; (line = reader.readLine()) != null; )
{
out.println(line);
}
}
finally
{
socket.close();
}
}
}
finally
{
listener.close();
reader.close();
writer.close();
}
}
}
any help and/or tips are greatly appreciated!
The reason is that after the first loop reading the input stream, you reach the end of it, then when you do the second loop, reader.readLine() just return null.
You have to call reset() before the second loop. e.g.
reader.reset();
for(String line; (line = reader.readLine()) != null; )
{
out.println(line);
}
EDIT
In your case, it may be better to open the reader and writer for each connexion and not once and for all. The same idea if you need to read first for a lookup then to send the content.

Code deletes the content of the file rather than replacing a text

In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

compiling java file from another java class

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String className = "str.java";
String command = "javac " + className;
String output = obj.executeCommand(command);
System.out.println(output);// prints the output of the executed command
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
I am trying to compile a Java file (str.java) from another Java class(ExecuteShellComand.java). What I am trying to do is if "str.java" compiles successfully then I want to execute "java str" command, but if the compilation fails then proper stacktrace or errors should be printed. I am storing the stacktrace or the errors in output variable.
But when I execute this code although "str.java" has somes errors in it System.out.println(output) is not printing the errors.
If you want to capture the errors from a command then you shall capture error stream instead of Input stream
So replace
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
with
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
The Process class tries to mimetize OS process. It means, process keep different output stream for error and normal messages and one stream for input. In UNIX, should be:
wc < file > wc.count 2> wc.error
In Java...
abstract InputStream getErrorStream()
Gets the error stream of the subprocess.
abstract InputStream getInputStream()
Gets the input stream of the subprocess.
abstract OutputStream getOutputStream()
So, you should use getErrorStream() to get errors..
Refactoring your code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String className = "str.java";
String command = "javac " + className;
obj.executeCommand(command);
System.out.println(obj.output);
System.out.println(obj.errors);
}
private String errors;
private String output;
private void executeCommand(String command) {
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
errors = readStream(p.getErrorStream());
output = readStream(p.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
private String readStream(InputStream inputStream) throws IOException {
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
return output.toString();
}
}

capture error from runtime process java

I'm running a Java program from another Java application using Runtime.getRuntime().exec like this
Process p1 = Runtime.getRuntime().exec("javac test.java");
Process p2 = Runtime.getRuntime().exec("java test");
The content of the test.java
import java.io.*;
class test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s);
}
}
I want to handle Input, Output and Error stream of the process p2.
I did capture of the output of the test.java, however, I do not know how to handle output and error.
Here is my code:
try {
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
bre.close();
p2.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception err) {
err.printStackTrace();
}
The code above works fine for capturing the output of the test.java. But it does not display error of the test.java.
Could you please give me a sample code for fixing this problem and handling output stream or share idea? Thanks in advance
The solution I've always used is to create a separate thread to read one of the streams
So, in your case it should be something like
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
new Thread(new Runnable() {
#Override
public void run() {
while ((s = br.readLine()) != null) {
System.out.println(s);
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
}
}).start();
// when you are finished close streams

Categories

Resources