package burak;
import java.io.*;
public class telcon {
public static void main(String[] args) {
try {
String[] command=new String[2];
command[0]="cmd /c start cmd.exe /k \"telnet\"";
command[1]="92.44.0.60";
Process p =Runtime.getRuntime().exec(command);
try {
p.waitFor();
} catch (InterruptedException e) {
System.out.println(e);
}
BufferedReader reader= new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
line=reader.readLine();
File file =new File("rapor.txt");
file.createNewFile();
FileWriter writer=new FileWriter(file);
StringBuilder responseData=new StringBuilder();
while(line!=null) {
System.out.println(line);
responseData.append(line);
writer.write(line);
writer.close();
}
BufferedReader stdInput=new BufferedReader(new InputStreamReader(p.getInputStream()) );
BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Error;
while((Error=stdError.readLine())!=null) {
System.out.println(Error);
}
while((Error=stdInput.readLine())!=null) {
System.out.println(Error);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
i want to run telnet execute some commands i have two problem first when i connect to telnet it ask me username and password how ı contineude execute commands by using code after the enter password and my second question inputstream is not working readline is empty all time how can ı fix this problems.thanks for hel
I recommend you the Apache Commons Net Java library (http://commons.apache.org/proper/commons-net/) which contains various clients for many Internet protocols, including Telnet. I don't recommend you to use the embedded telnet client from the OS. Things will be cleaner with a library.
In addtion, in your first while loop, you're closing the writer object every iterations, and you don't read further with your reader.
Related
Printed the data from two files in to console , now i want to merge the both data and print in one file using printWriter
for this am using the following code ,
import java.io.*;
class DataM
{
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new FileReader("abc.txt"));
BufferedReader br1=new BufferedReader(new FileReader("def.txt"));
String line=br.readLine();
while(line!=null)
{
System.out.println(line);
line=br.readLine();
}
System.out.println("****************************************************************************");
String line2=br1.readLine();
while(line2!=null)
{
System.out.println(line2);
line2=br1.readLine();
}
//PrintWriter pw=new PrintWriter();
PrintWriter pw=new PrintWriter("ilm.txt");
pw.println(br);
pw.println(br1);
pw.println();
pw.flush();
pw.close();
}
}
I see that you want to print the results of the two files in order, however you have taken the approach:
pw.println(br);
pw.println(br1);
This won't work because those two objects are instances of a Reader. A reader, when called to be a String won't return its contents. So our option here is to store those lines you printed and instead write to the file that way.
So, when you read those two files, let's do this
List<String> lines=new ArrayList<>();
String line=br.readLine();
while(line!=null)
{
System.out.println(line);
lines.add(line);
line=br.readLine();
}
System.out.println("****************************************************************************");
String line2=br1.readLine();
while(line2!=null)
{
System.out.println(line2);
lines.add(line2);
line2=br1.readLine();
}
This will store all those lines so we can write to a file ourselves.
Now to do that...
try(PrintWriter stream=new PrintWriter(new File("ilm.txt"))) {
lines.forEach(stream::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
This simply opens a new PrintWriter to write to the file with, similarly to what you have done, where we can write and close the stream automatically.
I am trying to invoke a command prompt and logging in some credentials into it. For this I am taking following approach:
public static void main(String[] args) throws InterruptedException {
// init shell
ProcessBuilder builder = new ProcessBuilder("cmd");
Scanner scanner = null;
BufferedWriter writer = null;
try {
scanner = new Scanner (System.in);
System.out.print("Enter your MS ID : ");
String user = scanner.nextLine();
System.out.print("Enter your MS Password : ");
String pass = scanner.nextLine();
Process p = builder.start();
writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write("oc logout");
writer.newLine();
writer.flush();
writer.write("oc login <private-url>");
writer.newLine();
writer.flush();
writer.write(user);
writer.newLine();
writer.flush();
writer.write(pass);
writer.newLine();
writer.flush();
//Writing this will end the process after login is done
// writer.write("exit");
// writer.newLine();
// writer.flush();
Thread t = new Thread(new Runnable() {
public void run() {
try(BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
;
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
p.waitFor();
} catch (IOException e) {
System.out.println(e);
}
finally {
scanner.close();
}
}
But when I run the program, it just does not end. Eclipse and running by cmd always need to explicitly exit the program. Maybe I am missing something. Any help would be greatly appreciated. It just works for the desired thing but does not exit and I need to integrate in my program and not able to do so.
You don't close the writer!
Your loop in the runnable task asks the reader whether it has more input:
while ((line = br.readLine()) != null) { ... }
This is always the case unless the writer in the main thread is closed. So for a quick solution put a simple writer.close() after the last writing action.
The better solution is to use the try-with-resources statement, introduced with Java 7. You should open your readers, writers, scanners, etc. as following:
try (Scanner scanner = ...) { ... }
try {Reader reader = ...) { ... }
try {Writer writer = ...) { ... }
These statements will handle the closing automatically for you. And as a side effect, it will make your code much more readable.
Warning: Closing a Scanner which is connected with System.in also closes the standard input, so that after that point no input can be read anymore. If that is not appropriate in your part of the code, then do not close the scanner.
I am writing a Java application in IntelliJ IDE. The application used Rserve package to connect to R and perform some functions. When I want to run my code for the first time, I have to launch R in the command line and start the Rserve as a daemon, which looks something like this:
R
library(Rserve)
Rserve()
After doing this, I can easily access all the function in R without any errors. However, since this Java code would be bundled as an executable file, so is there a way that Rserve() is invoked automatically as soon as the code is run so that I have to skip this manual step of starting Rserve using the command line?
Here is the code for the Class I wrote to get Rserve working from Java
public class InvokeRserve {
public static void invoke() {
String s;
try {
// run the Unix ""R CMD RServe --vanilla"" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("R CMD RServe --vanilla");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
// System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
I know this question has been asked a long back . I think You have the answer. But the below answer may help others. That's why I am posting my answer.
answer:- Instead of going again and again to the R console to start Rserve. One thing you can do is you can write a java program to start Rserve.
Below code you can use in a java program to start Rserve.
https://www.sitepoint.com/community/t/call-linux-command-from-java-application/3751. This is the link where you will get the code to run a linux command from java.I have changed the command only and posting below.
package javaapplication13;
import java.io.*;
public class linux_java {
public static void main(String[] args) {
try {
String command ="R CMD Rserve";
BufferedWriter out = new BufferedWriter(new FileWriter(
new File(
"/home/jayshree/Desktop/testqavhourly.tab"), true));
final Process process = Runtime.getRuntime().exec(command);
BufferedReader buf = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
while ((line = buf.readLine()) != null) {
out.write(line);
out.newLine();
}
buf.close();
out.close();
int returnCode = process.waitFor();
System.out.println("Return code = " + returnCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
i am trying to run commands using java program,but p.waitfor() function waits forever.What is wrong with the code?
import java.io.*;
public class doscmd
{
public static void main(String args[]) throws InterruptedException
{
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) {}
System.out.println("Done");
}
}
Is the directory large? Maybe p fills up its output buffer and stalls waiting for a reader to consume something so it can finish writing out the directory listing.
You should probably move
p.waitFor();
to the end of the method.
You have to access your InputStream and ErrorStream before you're calling waitFor(). You should take a look at that question too for more details on how it works.
Your directory structure is too large. Move your p.waitfor() to
Process p=Runtime.getRuntime().exec("cmd /c dir");
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
p.waitFor();
I tried running running this in C:\programfiles works fine.
Can someone help me in the below scenario,
I need to call a perl script from my java code. The perl script is an interactive code, which gets the input from the user during its execution and continues further to end. So, the example I have used is, the perl script when executed asks for the age by printing in the console "How old are you?", when the user enter some value say '26'. Then it prints "WOW! You are 26 years old!".
When I tried calling this script from my java code, the process waits till I give the value as 26 in the outputstream, while in the inputstream there is no value. Then finally when again I read the inputstream, i get the entire output of the script together. So, here can't I make it interactive?
I have went through many forums and blogs, but couldn't locate any, which exactly target my requirement.
Here is the java code
import java.io.*;
public class InvokePerlScript {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Process process;
try
{
process = Runtime.getRuntime().exec("cmd /c perl D:\\sudarsan\\eclips~1\\FirstProject\\Command.pl");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
out.write("23");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
process.waitFor();
if(process.exitValue() == 0)
{
System.out.println("Command Successful");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
System.out.println("Command Failure");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
catch(Exception e)
{
System.out.println("Exception: "+ e.toString());
}
}
}
Perl code is as below
$| = 1;
print "How old are you? \n";
$age = <>;
print "WOW! You are $age years old!";
Thanks in advance,
Sudarsan
Are you calling flush() on the OutputStream in Java after writing the values? If you don't, there's a good chance they'll just be held in the stream's buffer within the Java process, and so never make it to Perl (with the result that both processes end up waiting for the other's IO.)
(Depending on the implementation of the stream this may or may not be necessary, but it certainly wouldn't hurt - and I've been bitten by this in the past. Usually one doesn't need to be as careful, since flushing happens implicitly when close() is called, but here you can't close the stream after you've finished writing.)
It looks like you're trying to read a full line in this code:
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
...
However, in your perl code, you are not printing an endline character, so readLine never returns (as per the documentation).