I am trying to implement the Java 6 console api. If I am trying to run my java class as Java Application why is my console null? Or shall I be running my .java from command promt like c:workspace>java -cp . console
My console.java class
public class console{
public static void main(String s[])throws IOException
{
Console c=System.console();
if(c==null)
{
System.err.println("Console object is not available");
}
else{
String name = null;
name = c.readLine("Enter any String: ");
...}
Please see this bug. Seems like you'd need to use the command line.
Related
I'm making a Swing program which will be used to easily run C++ programs with G++, but I'm stuck on actually running the program. I tried using Runtime.getRuntime() or something like that, but it didn't seem to work. And also, using that only runs the command, and doesn't allow input. Obviously, as it'll run a program, it would need to be able to receive command line input, so is there any way to run a command by opening cmd and then executing the command in that instance of the program, allowing the user to type things in?
Have a look at the ProcessBuilder class, I think it does what you're asking: https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
How to run a command in cmd, and open it up to allow input? (Java)
First of all, are you making use of the arguments in the main method?
public static void main(String[] args) //<--- arguments will be send to args[x]
{
}
If you want your program to be able to receive arguments, you have to handle those received arguments, if not, even if the arguments were passed in. Nothing will happen.
Example:
class MyFullName{
public static void main(String[] args){
if(args.length() != 2)
system.out.println("2 arguments needed");
else
System.out.println("Your fullname is: " + args[0] + " " args[1]);
}
}
The above example is a program which receives the first name and last name and combine it together and printing it out. Arguments you typed will be passed into args string array.
Test run:
javac MyFullName.java
java MyFullName adam smith
Your fullname is adam smith
If you are using Windows and do not want to type the commands in the command prompt, you can place those codes in a batch file. Executing the batch file will execute those commands, which will launch your program.
This sample Java Program executes the 'dir' command reads the output of the dir command prints the results.
import java.io.*;
public class doscmd
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("cmd /c dir");
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}}
catch(IOException e1) {}
catch(InterruptedException e2) {}
System.out.println("Done");
}}
Ref:http://www.javasamples.com/showtutorial.php?tutorialid=8
I am trying to run Java programs in PHP using PHP's exec() function. But consider this sample program:
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.println("Hi " + name);
}//end main
}//end class MyProgram
But the problem is that when I execute one such program, I get the error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at HelloWorld.main(HelloWorld.java:7)
This is probably because on my web browser I have a console lacking. IDEs such as eclipse, netbeans, terminal/command prompt provide me with one, but how do I provide one for a web browser?
Sample PHP Code:
<?php
exec('javac MyProgram.java 2>&1');
exec('java MyProgram 2>&1', $output);
print_r($output);
?>
I need a way to run another java application from within my application. I want to recive its outputs into a JTextArea and send it inputs via a JTextBox.
Depends.
You could use a custom URLClassLoader to load the second applications jar and call the main classes main method directly. Obviously, the issue there is getting the output from the program ;)
The other solution would be to use a ProcessBuilder to launch a java process and read the output via the InputStream
The problem here is trying to find the java executable. In general, if it's in the path you should be fine.
You can have a look at this as a base line example of how to read the inputstream
UPDATED with Example
This is my "output" program that produces the output...
public class Output {
public static void main(String[] args) {
System.out.println("This is a simple test");
System.out.println("If you can read this");
System.out.println("Then you are to close");
}
}
This is my "reader" program that reads the input...
public class Input {
public static void main(String[] args) {
// SPECIAL NOTE
// The last parameter is the Java program you want to execute
// Because my program is wrapped up in a jar, I'm executing the Jar
// the command line is different for executing plain class files
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "../Output/dist/Output.jar");
pb.redirectErrorStream();
InputStream is = null;
try {
Process process = pb.start();
is = process.getInputStream();
int value;
while ((value = is.read()) != -1) {
char inChar = (char)value;
System.out.print(inChar);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can also checkout Basic I/O for more information
import java.io.*;
public class ConsoleDemo {
public static void main(String[] args) {
String str;
Console con;
con = System.console();
if (con == null)
return;
str = con.readLine("Enter a string : ");
con.printf("Here is your string %s", str);
}
}
I copied this code from the book, which says that I would get a prompt on the screen for entering a string, but my IDE just gives the message that the execution has termination, without giving me a prompt.
Eclipse nor Netbeans supports the use of Console. The Console.istty() method will return false and you will not have a console to use.
You can change your code to the following and achieve the same result and be able to run it from within the IDE.
import java.io.*;
public class ConsoleDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String and press enter");
System.out.println("You entered the String: " + scan.nextLine()
}
}
What IDE are you using? This code works just fine when you run it from the command line, so the problem clearly lies with the configuration of your IDE.
Use the following commands to compile and run your code from the command line:
javac ConsoleDemo.java
java ConsoleDemo
Edit: as this link suggests, using System.Console doesn't always work in IDEs. Alternatively you can just use System.in.
Your code is working from both Eclipse and Command Prompt.
Try this way as well if you are using Java 5 or +
Scanner in = new Scanner(System.in);
System.out.print("Enter a String : ");
String string = in.nextLine();
System.out.println("Here is your String : " + string);
By default, eclipse does not associate console with the JVM. You may have to configure it. But if you run it in command line, it will have console definitely and hence it will run without any problem.
It is because your IDE runs this code by javaw.exe (windowless -> no console) not java.exe (with console window) command, so System.console() returns null.
Standard solution is to read data from input stream which is represented by System.in so you can use for instance Scanner like
Scanner keybord = new Scanner(System.in);
String line = keybord.readLine();
How to mask a password from console input? I'm using Java 6.
I've tried using console.readPassword(), but it wouldn't work. A full example might help me actually.
Here's my code:
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args)
{
Console console = System.console();
console.printf("Please enter your username: ");
String username = console.readLine();
console.printf(username + "\n");
console.printf("Please enter your password: ");
char[] passwordChars = console.readPassword();
String passwordString = new String(passwordChars);
console.printf(passwordString + "\n");
}
}
I'm getting a NullPointerException...
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
You would use the Console class
char[] password = console.readPassword("Enter password");
Arrays.fill(password, ' ');
By executing readPassword echoing is disabled. Also after the password is validated it is best to overwrite any values in the array.
If you run this from an ide it will fail, please see this explanation for a thorough answer: Explained
Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");
If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:
# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"
jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}
# .. do something with 'password' variable ..
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"
See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"
The given code given will work absolutely fine if we run from console. and there is no package name in the class
You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.