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.
Related
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()
I am trying to read/write values from/to telnet process by means of ProcessBuilder.
public static void main(String[] args) {
try {
telnetProcess = new ProcessBuilder("C:\\Windows\\System32\\telnet.exe","x.x.x.x").start();
telnetInputReader = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream()));
telnetOuputWriter = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream()));
expectPattern("login:");
sendCmd("user");
expectPattern("password:");
sendCmd("pwd");
expectPattern("switch>#");
sendCmd("exit");
expectPattern("Connection to host lost");
} catch (IOException ex) {
System.out.println("Exception : " + ex);
}
}
I got the following error
java.io.IOException: Cannot run program "C:\Windows\System32\telnet.exe": CreateProcess error=2, The system cannot find the file specified
I tried to change the file path to unix formatted style like C:/Windows/System32/telnet.exe and no luck. (Though I expected it to not to work). Then copied the telnet.exe from it's location to some other user's home directory and I was not getting any errors. (???)
But, I didn't see the output as expected. I didn't get any response from the process and the code exited.
public static void sendCmd(String cmd) {
System.out.println(cmd);
try {
telnetOuputWriter.write(cmd + "\n", 0, cmd.length());
} catch (IOException ex) {
Logger.getLogger(TelnetProcessHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static String expectPattern(String pattern) {
String cmdResponse = "";
try {
String line = "";
// Always getting 'null' here
while ((line = telnetInputReader.readLine()) != null) {
System.out.println(line);
cmdResponse += line;
if (line.contains(pattern)) {
break;
}
}
} catch (IOException ex) {
System.out.println("ex : " + ex);
}
return cmdResponse;
}
What is wrong in this ? Then, one other query. I have tried using PrintWriter for writing to process which in turn has BufferedWriter in it, like,
telnetOuputWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream())));
Is this fine to use PrintWriter in this context ?
Note : Due to some reasons, I would like to stick with using telnet by means of process, not with Socket or TelnetClient or expect4j.
The telnet program does not use the standard input and output streams to communicate with the user, it needs to use the console device directly. You'll have to find an alternative way of doing what you're trying to do.
For example you could use a Java library that implements the telnet protocol. See this question for example: Open source Telnet Java API
Hello I am writing a client server code in Java. I am trying to provide the server the facility to add some values to a list. I am writing the following code for giving the server to take input
while (true) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
boolean isAdd=false;
String str=" ";
System.out.println("Do the server want to give input? yes/no");
//sc.next();
if(sc.nextLine().equals("yes")){
System.out.println("Enter The value:");
str=sc.nextLine();
System.out.println("To be Added or Removed? add/remove");
if(sc.nextLine().equals("add")){
isAdd=true;
}
}
sc.close();
System.out.println(str);
Thread t = new Thread(new ClientHandler(clientSocket, str.toString(),isAdd));
t.start();
And the following code is inside the run method
this.str=str;
System.out.println(str);
if(str!=" " && isAdd)
this.addElement(str);
if(str!=" " && !isAdd)
this.removeElement(str);
Path path=Paths.get("companies.txt");
try {
this.l=(ArrayList<String>) Files.readAllLines(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But the output is showing null pointer exception at the lines
Thread t = new Thread(new ClientHandler(clientSocket, str.toString(),isAdd));
if(str!=" " && isAdd)
this.addElement(str);
if(str!=" " && !isAdd)
this.removeElement(str);
I am totally stack why is it happening? Can anyone help me? I also checked the values at different points. No null value is coming.
I updated the code but I get still a null value in my textfield. In the console I can see everything from the file WandelaarBestand. Maybe It has something to do with converting number to string.But when I wan't to dat that with int getal I get nothing. Without int getal I get a Null value in my textfield but I can still see everething from my file in my console.
Here you can find my updated code.
public class geefInfo implements ActionListener {
public void actionPerformed(ActionEvent e) {
BufferedReader in;
String regel="";
int getal;
try {
in=new BufferedReader(new FileReader("WandelaarBestand.txt"));
while((regel=in.readLine())!=null){
getal=Integer.parseInt(regel);
System.out.println(regel);
}
in.close();
} catch (FileNotFoundException e6) {
e6.printStackTrace();
System.out.println("kan file niet vinden");
} catch (IOException e7) {
e7.printStackTrace();
System.out.println("fout bij lezen of sluiten file");
}
info.setText(""+regel);
}
}
in your second try block you print out the line - so far so good.
But your line:
String naam2=naam.getText();
does not make any sense, because naam is never set and in the follwing if statement you just use naam2, which is null as well.
Also try to close your reader, it can get messy if you don't.
Hope that helps a bit
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.