Java io handle is invalid exception - java

I have a function that reads from the console using readPassword(). This function is called several times in one program iteration. However, I keep getting a java io exception once it gets to the readPassword() line. I noticed when i removed the close() statement from the finally-clause this error disappears. Why does this happen and when should I properly close the reader?
public void Func()
{
Console console = System.console();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
if (console == null)
System.out.println("Error!");
try
{
char[] pwd = console.readPassword();
String password = new String(pwd);
System.out.println("PW: " + password);
String input = reader.readLine();
System.out.println("UserNm: " + input);
} catch (IOException e) {
System.out.println("IO EXCEPTION");
} finally {
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
System.out.println("error");
}
}
}
return null;
}
Thanks in advance for the help!

There's only one console, and there's only one System.in. If you close it, then you can't read from it anymore! You don't need to close that BufferedReader, nor should you. That whole finally block can and should just go away.
On closer reading, I don't even see why you're creating the BufferedReader in the first place -- it seems to have no function. Just delete all the code that deals with it!

You don't need any reader here, just use the Console instance.
public String Func() {
Console console = System.console();
if (console == null)
throw new IllegalStateException("No console available");
try {
String username = console.readLine("Username: ");
String pwd = new String(console.readPassword("Password: "));
return pwd;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Edited with your question edit. Just use the Console class, it can read/write, you don't need any reader/writer.

Use something like java.util.Scanner instead and as other people say don't worry about ever trying to close system.in.
So much cleaner:
Scanner in = new Scanner(System.in);
String password = in.nextLine();
String username = in.nextLine();
No tidy up/exception handling required.

You should not close your Console. Keep it open until your program does no longer need to read from it.

Related

Call a class whose name is in a string

I'm trying to call a class whose part of the name is included in a string obtained by reading console input.
static void menu() {
System.out.println("Choose a menu:");
System.out.print("\n");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String nome = null;
try {
nome = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("\n");
System.out.println("Opening: " + nome);
System.out.print("\n");
String funzione = nome + ".funzione();";
try {
Runtime.getRuntime().exec(funzione);
} catch (IOException e) {
System.out.println(funzione);
e.printStackTrace();
}
Basically, if I write "print", I'd like to execute print.function(); which is called later in the program. The code works but it also outputs an error java.io.IOException: Cannot run program "print.function();": error=2, No such file or directory, yet print.function(); gets executed anyway.
To be clear, I am intentionally following this method rather than a switch case.
I think I'm executing the process in a wrong way, could anyone highlight me where? Many thanks.

VM Terminated on static method

public static void main() {
String fileName = "cardNumbers.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
CreditCard card = new CreditCard(line);
if (card.creditCardType().equalsIgnoreCase("Unknown"))
{
System.out.println("Card number " + card.getCardNumber() + "is an unknown credit card type.");
}
else if (card.isValid())
{
System.out.println(card.creditCardType() + " number" + card.getCardNumber() + " is valid.");
}
else if (!card.isValid())
{
System.out.println(card.creditCardType() + " number " + card.getCardNumber() + " is not valid.");
}
}
}
catch (FileNotFoundException ex)
{
System.out.println("file not found exception thrown");
}
catch (IOException ex)
{
System.out.println("error while reading the file");
}
finally
{
System.exit(0);
}
}
When I run this method it just says ProcessCardNumbers.main(); VM Terminated. Instead of actually printing out the content.
If I add a print at the very start of the function or in the finally block, they are printed.
Im not sure why this is happening or how I can fix it.
As you told us that:
Adding a println at the start is printed
and
Adding a println in the finally works too
we can deduce that your code is working. It's just that when you reach while((line = bufferedReader.readLine()) != null), line stays null, so you never enter your while.
Why is that? Well, your file may be empty to begin with. If it is not, double-check the encoding of your file: it may not be using the proper returns symbols, hence not having a "completed line".
This seems that in your text file cardNumbers.txt has no data. When this program will execute within while loop bufferedReader.readLine()). will return null. So loop will terminate. After termination you have written System.exit(0); function in finally block which terminate JVM on the spot. So JVM is terminated now that's why you are not able to see anything after working of this code.
If you want to check working, write one SOP statement in finally block. Probably that will execute without termination of JVM.
The problem here is not the bug in your code but the design problem that does not let you see the bug.
You are probably getting an undeclared exception (RuntimeException) and the VM can't print it because you kill it before in the finally.
You have several options:
Remove the System.exit(0); and let it die normally. This may fail if there is another non-daemon thread running. You may try to stop it. You can, for example, cancel a Timer.
Add a catch (RuntimeException e) { section before the finally and print the captured error. e.printStackTrace(); should do the trick.
With any of those you should see the exception on console so you can fix it.
Your main method signature must look like this:
public static void main(String[] args)
instead of
public static void main()

Java - Stream is closed

I am running another jar with this code:
(I am updating a gui in some parts , so dont feel confused.)I get an IO Exception (Stream Closed) here:
if((line = readr.readLine()) != null){
Thats the full code:
if(!data.serverStarted()){
try{
data.updateConsole("Starting server!");
String fileDir = data.dir + File.separator + "craftbukkit.jar";
Process proc = Runtime.getRuntime().exec("java -Xmx2048M -jar "+"craftbukkit.jar"+" -o true --nojline");
data.setOutputStream(proc.getOutputStream());
InputStream is = proc.getErrorStream();
}catch(IOException ex){
ex.printStackTrace();
}
BufferedReader readr = new BufferedReader(new InputStreamReader(is));
data.setServerStarted(true);
String line;
while(data.serverStarted()){
try {
if((line = readr.readLine()) != null){
data.updateConsole(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
data.updateConsole("You have already started your server!");
}
You have a while loop that closes readr on every pass. The next time it gets to the try block, readr is closed. Perhaps you intended to put the try/catch block around the while loop?
You are closing the reader inside the loop that reads from it. You need to close it outside of the loop:
try {
String line;
while (data.serverStarted() && ((line = readr.readLine()) != null)) {
try {
data.updateConsole(line);
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
readr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am surprised that this code even compiles.
You declare the actual InputStream is inside the try/catch at the beginning, but that makes it only visible inside that block. So whatever you give to the BufferedReader a few lines below is something else and most likely not what you think it is.
In addition your while(data.serverStarted()) does not check if the stream is still open, and later you only use a single if check (again with no check if the stream is open), so you'll only read one single line at best.
I have a feeling that you had a bad OutOfCoffeeException while writing this code. ;)

Trying to output a string variable to a .txt file within an IF statement. - Java

I'm pretty new to java and i still have alot to learn. I'm trying to output the data within a variable to a text file, and I'm not sure why this will not work. Could anyone help me out?
if ("Y".equals(output_to_file)) {
System.out.print("You selected Yes");
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream("filename.txt"));
out.print(first_input);
}
finally {
if (out != null) out.close();
}
}
else System.out.print("You selected No");
"(new FileOutputStream("filename.txt"))" is underlined red, and it says: Unhandled exception: java.io.FileNotFoundException
Thanks for your help!
Anytime you're doing file operations, there is the possiblity that a FileNotFoundException will be thrown. Therefore, Java wants you to tell it what to do in the event that one is thrown. Thus, you need to add a catch clause for the possible FileNotFoundException. You already have a try block, so you simply need to add a catch clause before your finally clause:
try {
out = new PrintStream(new FileOutputStream("filename.txt"));
out.print(first_input);
}
catch(FileNotFoundException e) {
//do something in the event that a FNFE is thrown
}
finally {
if (out != null) out.close();
}
}

url connection question

I'm reading a URL with the following code:
URL myURL = new URL("htpp://path_to_my_file");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(myURL.openStream()));
while (reader.ready()) {
String line = reader.readLine();
...
}
} catch (IOException e) {
throw new RuntimeException("Parsing of file failed: " + myURL, e);
}
Could it happen, that the file is not read completely? (because of network problems or something else?). If yes, is there a way to test it or even to avoid?
The background: I'm working on an application (not written by me up to this point) and users report me that parts of files are missing sometimes. It happens sporadically so my only guess was that something sometimes fails when the file is read in but I have too few java-background to be sure...
Yes, you'll know it's happened when you get an IOException as per the Reader.readLine docs.
So you'll want to catch the Exception, something like this:
try {
while (reader.ready()) {
String line = reader.readLine();
}
}
catch(IOException e) {
// Bah! Humbug!
// Should really log this too. So if you're using Log4j:
log.error("Error reading from URL " + myURL.toString(), e);
} finally {
try { if (reader != null) reader.close(); }catch(Exception e){}
}
Somewhere here, I found the following comment:
ready() != has more
ready() does not indicate that there is more data to be read. It only shows if a read will could block the thread. It is likely that it will return false before you read all data.
To find out if there is no more data check if readLine() returns null
It sounds that the implementation with reader.ready() causes my problem. Am I wrong with this assumption?

Categories