i am trying to use Console class in java. with this code
import java.io.Console;
public class ConsoleClass {
public static void main(String[] args){
Console c=System.console();
char[] pw;
pw=c.readPassword("%s","pw :");
for(char ch:pw){
c.format("%c",ch);
}
c.format("\n");
MyUtility mu =new MyUtility();
while(true){
String name=c.readLine("%s", "input?: ");
c.format("output: %s \n",mu.doStuff(name));
}
}
}
class MyUtility{
String doStuff(String arg1){
return "result is " +arg1;
}
}
here i am getting NullPointerException when i tried to run in netbeans but i am not getting any Exception when tried to run in cmd with out netbeans IDE.Why?
static Console console()
Returns the unique Console object associated with the current Java virtual machine, if any.
If any.
http://download.oracle.com/javase/6/docs/api/java/lang/System.html
Consoles are typically associated with processes that run independently of frameworks. They are a means of interfacing a process's standard input and output with a shell. If your classes are running as a component of a larger framework, the framework may own the console, and your program might not have a console at all.
There are other conditions and techniques to launch a program without a console. They are typically used when the destruction of the console is guaranteed to occur, but you want the program detached in such a manner that the console's destruction doesn't signal the program's termination.
As such, you cannot guarantee the existence of a console; but, if you are going to run your program in an environment where the console is likely to be present, you should take advantage of it.
System.console() returns a Console instance if a console is associated with the process. - Running under NetBeans you likely don't have an associated console.
Related
I have written a sample code:
import java.util.Scanner;
public class abcd {
public static void main(String[] args) {
System.out.print("please enter a: ");
Scanner a = new Scanner(System.in);
String b = a.next();
System.out.println(b);
}
}
I am able to compile and execute this code via Ubuntu terminal. In SciTe, it compiles fine, but when I run it, I am faced with this error:
please enter a: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at abcd.main(abcd.java:8)
Any Suggestions?
EDIT: When I execute a file in terminal, I do: 'java abcd' Scite does: 'java -cp .abcd'. How are the two commands different and why isn't java -cp working?
It appears that there is a bug/improper implementation in the handling of standard input in SciTE on Linux/Unix.
The description of the bug and a workaround are in this PDF document: A Problem with SciTE Go Command on Linux
Note: this is not official documentation, but it seems to match your problem.
According to that document, when running a Java program through the "Go" command on SciTE, input is supposed to come from the output pane. However, on Linux this does not work properly, and it's as if you are reading from an empty stream.
When you are reading from an empty stream, Scanner sees the end-of-file marker when it attempts to read a value using next(), nextInt() etc. And it throws a NoSuchElementException as there is no input element in the stream.
Your options to work around this problem:
Try the method mentioned in the aforesaid document, to use "Go" in a Linux terminal instead of the output pane.
Run the program in a terminal and avoud the "Go" command altogether.
Use a different IDE which doesn't have this problem.
Try to use hasNext() before next();
import java.util.Scanner;
public class abcd {
public static void main(String[] args) {
System.out.print("please enter a: ");
Scanner a = new Scanner(System.in);
while(a.hasNext()) {
try {
String b = a.next();
System.out.println(b);
} catch (NoSuchElementException e) {}
}
}
}
I don't mean to offend, but using hasNext() as suggested in Alexander's answer won't solve this problem, it will only enable OP to handle it well. I don't think that is what he/she is looking for.
Now I am no expert by any means and for some reason your program code works on my machine... But anyways, a NoSuchElementException is thrown when your program is cycling over an iterable object and there is nothing more to cycle over, despite your program expecting something there. A quick look-up in the Java-docs of Scanner.next()
shows that this exception is thrown if there are no more tokens available for read.
Now, if I had to guess I would advise you to try using something other than Scanner.next() and see if that works.
The fact that it works on my machine but not on yours is somewhat surprising, so could you provide some information on how you try to run your program? Are you running it from the default command-line? Or within Scite? (If second is the case, I really won't be able to help you, I have never even touched Scite).
I'm a beginner. Just wondering why this code works perfectly fine in windows command prompt, but I get an:
Exception in thread "main" java.lang.NullPointerException
at Test1.main(Test1.java:13)
error in eclipse. This has happened a lot to me, and it's really stopping me from using eclipse.
Here's the code:
import java.io.Console;
public class Test1 {
public static void main(String[] args) {
Console myConsole = System.console();
for (int a = 0; a < 10; a++){
int a2 = a * a;
myConsole.printf("\n%d squared is: %d.",a,a2); //Problem with this line
}
System.exit(0);
}
}
The javadoc for System.console() states
Returns The system console, if any, otherwise null.
Eclipse must not associate a system console.
Use System.in instead, possibly with a java.util.Scanner for input. And System.out for output.
Simply put, System.console() is returning null in Eclipse, but not when run in a console. This is the documented behaviour:
Returns the unique Console object associated with the current Java virtual machine, if any.
Returns:
The system console, if any, otherwise null.
Why not just use System.out instead? After all, you don't need any of the functionality of Console.
System#console may return null in certain environments. Since youre simply outputting to the console, you don't need to use Console. Formatter can be used instead:
System.out.printf("\n%d squared is: %d.", a, a2);
I want to make a Java program that reads a Password from STDIN silently. I mean, without outputting any pressed chars to the terminal and keeping it hidden from commandline history and the operating system processlist ps.
The class java.io.Console may be useful:
System.console().readPassword();
This reads a sequence of chars from the console, without echoing anything.
Note that it only works when you launch your java application with a real console. Otherwise, System.console() returns null.
A less secure option to get the password via STDIN that works with background jobs, virtual consoles, and normal consoles:
This is more compatible and less secure, it should work with your virtual console in your IDE, for background processes that don't have a TTY, and normal consoles. When a console is not found, it falls back to use a BufferedReader which will expose the password to screen as the user types it in some cases.
Java Code:
import java.io.*;
public class Runner {
public static void main(String[] args) {
String username = "Eric";
try {
ReadMyPassword r = new ReadMyPassword();
char[] password = r.readPassword(
"Hey %s, enter password to arm the nuclear wessels>", username);
System.out.println("Exposing the password now: '" +
new String(password) + "'");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ReadMyPassword{
public char[] readPassword(String format, Object... args)
throws IOException {
if (System.console() != null)
return System.console().readPassword(format, args);
return this.readLine(format, args).toCharArray();
}
private String readLine(String format, Object... args) throws IOException {
if (System.console() != null) {
return System.console().readLine(format, args);
}
System.out.print(String.format(format, args));
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
return reader.readLine();
}
}
Here's what it looks like through through the Eclipse virtual console:
Hey Eric, enter password to arm the nuclear wessels>12345
Exposing the password now: '12345'
Program Sisko 197 ready for implementation on your command
Here's what it looks like through the normal console.
el#apollo:/home/el/bin$ java Runner
Hey Eric, enter password to arm the nuclear wessels>
Exposing the password now: 'abcdefg'
Program Sisko 197 ready for implementation on your command
el#apollo:/home/el/bin$
You might want to give java.io.Console a look
It has a readPassword method which "Reads a password or passphrase from the console with echoing disabled".
Most secure option for Java to get a password with STDIN:
This demonstration is with Java on an Ubuntu 12.10 terminal. Grabbing the password with STDIN is a good idea security wise, since the password is not exposed to command line history or within the processlist with ps. The password letters typed are thrown away and not stored.
Java Code:
public class Runner {
public static void main(String[] args) {
System.out.print("Enter password: ");
String secretpassword = new String(System.console().readPassword());
System.out.println("Here we expose our password to STDOUT: "
+ secretpassword);
//Put maximum levels of encapsulation and security on this
//secretpassword variable. Destroy it in memory asap, don't leave it
//sitting around anywhere.
}
}
Conditions if you use the above code
If super high security is your top priority don't even store that password in a String. Encrypt it immediately after receiving it from the user. That way if some clever person scans the memory of your program, they won't find your plaintext password there.
If you try to run this program through a background job scheduler, then it is possible that System.console().readPassword() will return a NullPointerException which is a feature to enhance security. It denies access to shenanigans like virtual consoles and background tasks. If you want it to work right with virtual consoles see my other answer on this page.
If you try to run this code through an IDE like Eclipse, Netbeans or any other virtual console, then System.console().readPassword() will throw a NullPointerException because no real console is found, and the program will halt. This is a feature, not a bug.
What is looks like on the console:
el#apollo:/home/el/test$ java Runner
Enter password:
Here we expose our password to STDOUT: foobarpassword
el#apollo:/home/el/test$
I just wanted to know if there is some way to switch between console mode and graphical mode. I am using java on swing.
I'd like to know if I can type something in the shell to go to a console mode, then type something to go back to the desktop. Or if I can press some key at boot time, or something.
The idea is to make my server run in console mode, but have desktop available when I want to easier make my tasks.
You can use java.awt.GraphicsEnvironment.isHeadless() to check whether the environment where your program is running supports GUIs or not:
public static void main(String[] args){
if (GraphicsEnvironment.isHeadless()){
// Run console mode
} else {
// Start in GUI mode
}
}
If I were you, though, I'd make this a command-line switch so you can use the console mode in graphic environments, too. For maximum convenience, this would be a non-mandatory option which defaults to some kind of "auto" option, which uses the isHeadless check, like:
public static void main(String[] args){
final List<String> arguments = Arrays.asList(args);
final int modeIndex = arguments.indexOf("-mode");
final String mode = modeIndex == -1 ? "auto" : argument.get(modeIndex);
if ("auto".equals(mode)) runAuto();
else if ("console".equals(mode)) runConsole();
else if ("gui".equals(mode)) runGui();
else System.err.println("Bad mode: " + mode);
}
private static void runGui(){ ... }
private static void runConsole(){ ... }
private static void runAuto(){
if (GraphicsEnvironment.isHeadless()) runConsole();
else runGui();
}
(TODO: Add error handling, remove magic string literals, etc.)
So, start your program with java YourMainClass or java YourMainClass -mode auto and it makes an educated guess whether you want GUI or console, use java YourMainClass -mode console to force console mode, or java YourMainClass -mode gui to force GUI mode.
You can divide the project in two: the server and the GUI. You can run your server as a service (Windows) o daemon (Linux) and when you want the GUI, you have to launch and operate with it.
It´s like applications as MlDonkey, Ettercap, etc.
You can pass parameters on the command line and examine them in main(String[] args). They'll end up in args. So the most simply way is to check for args.length > 0 && "-c".equals (args[0]) to tell the program to run in console mode and to open a UI otherwise.
Another option is to write two main() methods (in different classes) and use the right one.
In the program you can define commands to hide the GUI. Something like gui.setVisible(false) should do the trick, it hides the window referenced by gui and all elements of it.
You could create a command line command that starts a GUI wizard that enables you to easily create the components/ configuration you want, and then enable the GUI to pass the complicated instruction back into your single application thread. Whether it is useful to have the GUI component destroyed after you have used it, or just hidden, is a decision you will have to make, regarding how often you will be using the GUI component.
I tried the java.io.Console API using eclipse. My sample code follows.
package app;
import java.io.Console;
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Console console = System.console();
console.printf("Hello, world!!");
}
}
When I tried running the example, I got the following error.
Exception in thread "main"
java.lang.NullPointerException at
app.MainClass.main(MainClass.java:11)
Where did I go wrong? Thanks.
Since you've mentioned in a comment that you're using Eclipse, it appears that there is currently no support for Console in Eclipse, according to this bug report.
The System.console method returns a console associated with the current Java virtual machine, and if there is no console, then it will return null. From the documentation of the System.console method:
Returns the unique Console object associated with the current Java
virtual machine, if any.
Returns:
The system console, if any, otherwise null.
Unfortunately, this the correct behavior. There is no error in your code. The only improvement that can be made is to perform a null check on the Console object to see if something has been returned or not; this will prevent a NullPointerException by trying to use the non-existent Console object.
For example:
Console c = System.console();
if (c == null) {
System.out.println("No console available");
} else {
// Use the returned Console.
}
System.console returns null if you don't run the application in a console. See this question for suggestions.
System.console returns the unique Console object
associated with the current Java
virtual machine, if any.
you have to test if console is null before using it.