Java BufferedReader.readLine() not waiting for user input - java

I am having an issue with my instance of BufferedReader not waiting for the user to input before moving forward.
static BufferedReader in;
public class {
public static void main(String[] args) {
try{
in = new BufferedReader(new InputStreamReader(System.in));
String input;
System.out.println("prompt");
input = in.readLine();
if(input.equals("Y")){
//do something
}else {
//do something else
}
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
What happens is I when I run the program, it simply skips over the in.readLine() and throws a null exception at the if statement. I am at a loss on what is happening, as I used the same code for another project that still works.
Thanks!

Found the answer. Using gradle to run the program and my task didn't have the parameter for standardInput = System.in. Still getting used to project building software!

Yes you have to treat the exception, just add this:
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
String input;
System.out.println("prompt");
input = in.readLine();
if(input.equals("Y")){
System.out.println("it works !!");
}else {
System.out.println("it's not a Y :(");
}
}

Related

BufferedReader with new InputStreamReader(System.in) throws an exception Temporarily unavailable resource

In my standalone application I have to read the user input from console in different classes.
I created a static class member variable in Installer class
public static final BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
but Installer.buffReader.readLine(); throws an IO exception - "Temporarily unavailable resource" sometime
public static void startApplication() {
System.out.println("Would you like to start the application? [y/n]");
String userChoice = null;
try {
userChoice = Installer.buffReader.readLine();
if (userChoice != null && userChoice.equalsIgnoreCase("y")) {
start();
}
} catch (IOException ex) {
LOGGER.error("Exception occured in startApplication() :{}", ex.getMessage());
}
}
How can I debug or prevent it?
I think is because you are calling here to the same method:
if (userChoice != null && userChoice.equalsIgnoreCase("y")) {
startApplication();
}
so the second time you call the method is throwing you the exception because the bufferedReader is still opened.
Try to close the bufferedReader before with buffReader.close(). Or don't use the static for BufferedReader because if other part of the app is using it, you will have a exception as well.
EDIT:
I was searching a little bit in google and can be because your operative system that is blocking the input for any reason. I tried your code and for me is not failing. Check here is a similar case: Link

Buffered reader causing an infinite loop

I'm currently doing a test project to understand how to read/write into a text file. This is my code:
package testings;
import java.util.Scanner;
import java.io.*;
public class Writing_Reading_files {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
File testFile = new File("testFile.dat");
String test, sName;
try{
PrintWriter print = new PrintWriter(new BufferedWriter(new FileWriter(testFile)));
test = in.nextLine();
print.println(test);
print.close();
}catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
try {
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
while(readerName != null) {
sName = readerName.readLine();
System.out.println(sName);
}
readerName.close();
} catch(FileNotFoundException e) {
System.out.println("FileNotFound");
System.exit(0);
} catch(IOException e) {
System.out.println("IO exception");
System.exit(0);
}
}
}
The while loop results in spitting out the line I put then nulls for an infinite loop if I try While(readerName.readLine != null) it stops the infinite loop but only outputs a null and I don't know where to go from there, I've tried following a youtube tutorial but he has it the same as my code so I'm unsure why I'm null keeps repeating. Thanks in advance for any help.
why would readerName become null? Maybe you mean that the String returned by readLine is null?
Consider
BufferedReader readerName = new BufferedReader(new FileReader(testFile));
String sName = readerName.readLine();
while(sName != null) {
System.out.println(sName);
sName = readerName.readLine();
}
Also consider using try-with-resources when opening your file.

Trying to read the console from past prints Java

I am trying to print out a message based on whether or not a previous specific message was printed. Here is my code:
public class Main {
public static Runnable getRunnable() {
return () -> {
System.out.println("Hello from a thread");
};
}
public static void main(String[] args){
new Thread(getRunnable()).start();
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
if (name.equals("Hello from a thread")) {
System.out.println("Hi!");
} else {
System.out.println("That's not nice");
}
}
}
I know that Scanner is probably no the solution here, but whenever I try something else like System.console.readLine(), which is probably also not correct, it prints out a NullPointerException. What am I supposed to use here to read previous output?
UPDATE: Hey, I tried it again but it didn't work out... not sure why again. Here's my updated code
public static ByteArrayOutputStream baos = new ByteArrayOutputStream();
public static PrintStream ps = new PrintStream(baos);
public static PrintStream old = System.out;
public static Runnable getRunnable() {
System.out.println("Hello from a thread");
return () -> {
System.setOut(ps);
System.out.println("Hello from a thread");
};
}
public static void main(String[] args){
new Thread(getRunnable()).start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
System.out.println("Somethings wrong!");
}
System.out.flush();
System.setOut(old);
if (baos.toString().equals("Hello from a thread")) {
System.out.println("Hello other thread!");
}
}
}
System.out is not System.in
System.out is the standard output stream, which usually prints to console. System.in is the standard input stream, which usually is taken from console. You can do setOut, setIn, and setErr to change the I/O streams, so for your case, you would need to redirect in to read from a source and out to output to that source. You may consider using an ArrayList to store and retrieve the output / input:
final List<Integer> list = new ArrayList<>();
System.setOut(new PrintStream(new OutputStream() {
public void write(int b) {
list.add(b);
}
}));
System.setIn(new InputStream() {
public int read() {
if (list.size() == 0) return -1;
return list.remove(0);
}
});
(Note that for various reasons, you probably want to do setErr so you can still output things properly.)
You can try a working example of this here

.java file to run another .java (frames) through Process

Real Goal: create a program that calls other programs(lab exercises)
Current goal: Make Main.java run Lab4 a GUI program (Lab4Ans201506159.java - the filename)
Lab4Form and Lab4Intro are forms
here is the Main.java code
public class Main {
public static void main(String[] args) throws IOException {
// TODO code application logic here
Process p,p2,p3,p4;
p = Runtime.getRuntime().exec("javac Lab4Ans201506159.java");
//p3 = Runtime.getRuntime().exec("javac Lab4Ans201506159Form.java");
//p4 = Runtime.getRuntime().exec("javac Lab4Ans201506159Intro.java");
p2 = Runtime.getRuntime().exec("java Lab4Ans201506159");
//p2 = Runtime.getRuntime().exec("Lab4Ans201506159");
}
and here is the Lab4 code
Lab4Form and Lab4Intro are Frames
what Lab4 is trying to do displaying Lab4Intro, and when it is closed, Lab4Form would be visible
public class Lab4Ans201506159 {
public static void main(String[] args) throws InterruptedException {
Lab4Ans201506159Intro intro = new Lab4Ans201506159Intro();
intro.setLocationRelativeTo(null);
intro.setVisible(true);
Thread.sleep(2000);
//Lab4Ans201506159Form form = new Lab4Ans201506159Form();
while(intro.isActive())
{
}
if(intro.isActive() == false){
Lab4Ans201506159Form form = new Lab4Ans201506159Form();
form.setLocationRelativeTo(null);
form.setVisible(true);
}
}
Problem: Running Main.java will result to a "BUILD SUCCESSFUL" in the compiler but no GUI is displayed. I need answers why it does not display or work.
I suspect only the first Process is executed, in order to be sure, have you already tried to redirect the output of Runtime.exec to the standard output
something like that:
public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(new FileOutputStream("log.txt")));
System.out.println("Init...");
try {
String line;
Process p = Runtime.getRuntime().exec( "javac Lab4Ans201506159.java" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
Thread.sleep(1000);
Process p2 = Runtime.getRuntime().exec("java Lab4Ans201506159" );
BufferedReader in2 = new BufferedReader(
new InputStreamReader(p2.getInputStream()) );
while ((line = in2.readLine()) != null) {
System.out.println(line);
}
in2.close();
}
catch (Throwable e) {
e.printStacktrace();
}
}
like that you can verify what is going wrong...
good luck
I managed to finish my end goal which is to open Lab4. I sort of took a different method though. I suspect one of the reasons why it does not work is because my classpath must have been wrong. I could say that because I can't compile (javac) in CMD Prompt. So I fixed that, then I 'clean and build' (using Netbeans) the project(lab4,intro,form). After that, in the last line of the compiler there will be a line like "java -jar C:\sdfsafs\blablabal". That was the line I used inside runtime.exec() and it finally worked.
public static void main(String[] args) throws Exception {
try {
runProcess("java -jar \"C:\\Users\\Aldrin\\Desktop\\201506159AnsLab4\\dist\\201506159AnsLab4.jar\"");
//runProcess("dir");
//runProcess("java Lab4Ans201506159");
} catch (Exception e) {
e.printStackTrace();
}
}
I still have not answered why the original code does not work though.

Exception handling code doubt

I am very new to this topic. Please bare with my silly doubts. I have the following code where I get a name from user and if its null sone exception is thrown. But here i m not getting any exception it i enter null. Please help me
import java.io.*;
class dbz
{
public static void main(String args[])
{
String s=null;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s=br.readLine();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
System.out.println(s);
}
}
You will never receive null as user input from the console, and it would not trigger a IOException regardless.
modify your code as below then you'll see the problem for yourself
import java.io.*;
class dbz
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(br.readLine());
}
}

Categories

Resources