This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
System.Console() returns null
Code:
public class Demo {
public static void main(String[] args){
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}else {
System.out.println("Console is.");
System.exit(0);
}
}
}
always No console. Why ? How to fix? Thanks.
You don't have any console associated.
As per javadoc
Returns the unique Console object associated with the current Java
virtual machine, if any, otherwise null
EDIT:
From Console javadoc.
Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.
Related
This question already has answers here:
Calling Java from Python
(9 answers)
Closed 7 years ago.
I need to find a way of communication between java and python program. My application is Java, and another application ( python) will request me some data and trigger some process in my Java Application.
EDITED: My application is Java desktop application, that uses Jboss Application server.
For first release, I do not have enough time to make a comprehensive way of communication. So I am planing to use subprocess.Popen for first release. I will provide them a jar. Then they can call me from pyhton.
Actually I was planned to make a single class that takes some arguments on main. Then according to parameters, my application can determine to call related function.
But there is a problem here. When they want to call my functions in following way. in each call, a new java process will be created and I can not keep some static variables from my application. Actually What I need is to run my application once, then access some functions from existing process.
#!/usr/bin/env python
from subprocess import Popen, PIPE
p = Popen(['java', '-jar', 'myjarfile.jar'], stdin=PIPE, stdout=PIPE)
Do you think Can I implement this using subprocess.Popen. If not can you show me an easy way ?
I would suggest using xmlrpc -- it's pretty simple:
import org.apache.xmlrpc.*;
public class JavaServer {
public Integer sum(int x, int y){
return new Integer(x+y);
}
public static void main (String [] args){
try {
System.out.println("Attempting to start XML-RPC Server...");
WebServer server = new WebServer(8080);
server.addHandler("sample", new JavaServer());
server.start();
System.out.println("Started successfully.");
System.out.println("Accepting requests. (Halt program to stop.)");
} catch (Exception exception){
System.err.println("JavaServer: " + exception);
}
}
}
(Source http://www.tutorialspoint.com/xml-rpc/xml_rpc_examples.htm)
Here's some code for a python client:
import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8080/")
today = proxy.today()
(Source: https://docs.python.org/3/library/xmlrpc.client.html)
All you'd have to do is make your methods and stitch them together.
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);
This question already has answers here:
How to implement a single instance Java application?
(17 answers)
Closed 2 years ago.
I have a program in Java (with a swing gui), and I would like only 1 instance ever to exist. If it attempted to open another instance of the program I would like the current instance to be brought to the foreground.
How do I do this?
Thanks in advance.
Launch the application using Java Web Start and implement the SingleInstanceService of the JNLP API. Here is a demo. of the SingleInstanceService.
If it attempted to open another instance of the program I would like the current instance to be brought to the foreground.
Hook that up in the newActivation(String[]) method of the SingleInstanceListener. It will be passed any arguments that were provided for the new launch. The existing instance gets to decide what to do with the new args (e.g. change file, add new tab, ignore..)
You can do it using a ShutDownHook and a lock file , see this simple example .
I think that it is the simplest way ...
There is no prev-instance in Java, but you can create a pid file in the temp (or /var/run) directory. (And make it File.deleteOnExit() to clean it anyway on exit)
To bring the existing window to top, you may notify the program yourself, thru named pipe, unix socket, or java remote method call, etc. A simple & dirty way is to write to a small file, say $TEMP/foobar-app.bring-to-top, and the program should periodically poll this small file, if it comes to exist, bring the window to top and remove this small file.
I guess Java couldn't handle signals, i.e., kill -HUP PID may not work for Java applications. Even if it could, not every OS have signals.
I did this once with a Socket and a ServerSocket:
First, when you start your application, make a ServerSocket listen on some port, for example 4004. The trick is to check whether it throws an IOException. If it does, there either is another application running or the port is used by another application (check this list for commonly used ports; Note that TCP and UDP ports are not blocking each other), otherwise you can continue with your application startup. If an instance is currently running, you might want to notify it by connecting a TCP Socket (which guarantees that your connection arrives; UDP doesn't).
Here is an example:
ServerSocket ss = null;
try {
ss = new ServerSocket(4004);
} catch (IOException ex0) {
// Port either occupied by your application or a foreign one
// -> Connect
Socket s = null;
try {
s = new Socket();
} catch (Exception ex1) {
// Something went wrong
}
if (s != null) {
// Send some singnal
}
}
if (ss == null) {
// Close or do something else
}
(I wrote this out of my memory, so some things might be wrong or could be done better).
In C# you usually create a Mutex at Applicaiton start. If you cannot create/get it, another instance of the application is already running. Unfortunately I am not 100% sure if this behaves the same in Java or what the exact syntax is.
Hope this helps.
Pattern singletone:
class SingleInstance {
private static SingleInstance instance;
public SingleInstance getInstance() {
if (instance==null)
instance = new SingleInstance();
return instance;
}
private SingleInstance() {
//construct it!
}
}
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.
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.