I have been trying to get data to be written from command prompt to a JTextArea, but it doesn't want to work for me, so I tried writing the data to a text file. SO far it writes one line then stops, so I need to continuously read from the text file until I stop it. Here is my code: `
try {
File consoleLog = new File("tempConsole.txt");
Process p = Runtime.getRuntime().exec("cmd /c minecraft.lnk");
//writes the text from the console to tempConsole.txt
BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream()));
BufferedWriter consoleOutputWriter = new BufferedWriter(new FileWriter("tempConsole.txt"));
consoleOutputWriter.write("" + input);
consoleOutputWriter.newLine();
//reads the tempConsole.txt
BufferedReader consoleOutputReader = new BufferedReader (new FileReader("tempConsole.txt"));
//writes the tempConsole.txt to the on-sceen JTextArea.
String outputFromTemp = consoleOutputReader.readLine();
console.setText(outputFromTemp);
consoleOutputWriter.close();
} catch (Exception ex) {`
Thank you for your help, I have been scouring my brain and the internet for hours with no luck :/
BufferedReader in = new BufferedReader(new FileReader(fileName))
String line2;
while ((line2 = in.readLine()) != null) {
//do something
}
Related
I'm trying to code my own little Java IDE in Java. I'm pretty far for what I want, because I only want to be able to code simple command-line-programs in my IDE.
My current problem has to do with user input.
This is how I handle having an own console-output in my IDE (outputField is a jTextArea):
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader readerInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader readerError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
//BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String outputLine;
while ((outputLine = readerInput.readLine()) != null) {
outputField.append(outputLine + "\n");
}
while ((outputLine = readerError.readLine()) != null) {
outputField.append(outputLine + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
But I have no idea how I could get user input to satisfy the scanner if a user written console-application asks for user input via a scanner. Right now my IDE would just freezes. Probably because the command-line-program waits for user input? Maybe I should run it in a different thread. How would I do that?
Maybe someone can get me some keywords I could research etc.
Greetings,
Daniel
I have a requirement, where I will be executing a batch file in java. On completion, the batch script waits for the user input. Then I have to pass two commands, each command followed by the enter key. Please find my code below,
File batchFile = new File("batch file path");
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
builder.command(batchFile.getAbsolutePath());
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
process.getOutputStream()));
String s;
loop:
while ((s = reader.readLine()) != null) {
System.out.println("$: " + s);
if (s.contains("last line before user input. so i am breaking here")) {
break loop;
}
}
writer.write("Command1");
writer.newLine();
writer.flush();
writer.write("Command2");
writer.newLine();
writer.flush();
writer.write("/close");
writer.newLine();
writer.flush();
writer.close();
while ((s = reader.readLine()) != null) {
System.out.println("$: " + s);
}
Issue:
Though I am sending input through the bufferedwriter, the process is not getting the input.Can someone give me any pointers to fix this issue. The program runs till the last while loop. When it enters the last while loop statement, it is getting hanged. It looks like the process is still waiting for the user input, so reader.readLine() in the while statement waits infintely. I have been searching for a solution for the whole day, but still no luck. Any help is appreciated.
I am trying to run a .exe file from a java application and would like to be able to use it (for now) like a terminal where i can write to the .exe then read back from it before writing it again.
My issue is that the code only works when the writer is closed before the reader attempts to read from the inputstream.
String line = "", prev = "";
Scanner scan = new Scanner(System.in);
ProcessBuilder b = new ProcessBuilder("myexe");
b.redirectErrorStream(true);
Process p = b.start();
OutputStream stdin = p.getOutputStream();
InputStream stdout = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
System.out.println ("->");
while (scan.hasNext()) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
String input = scan.nextLine();
if (input.trim().equals("exit")) {
writer.write("C");
} else {
writer.write(input);
}
writer.flush();
//writer.close();
while ((line = reader.readLine ()) != null) {
System.out.println ("[Stdout] " + line);
if (line.equals(prev)){
break;
}
prev = line;
}
reader.close();
}
So my question is, am i doing something wrong with the ProcessBuilder? I have read about not reading the output correctly can cause the system to hang. But this doesnt explain why it hangs when the writer is still open?
The issue was actually with my C compiled .exe. When it was running, the application was printing an output, therefore working in cmd terminal however i had not flushed the buffer after each command sent. Once i had done this, the java application would recognise each command as they were sent.
I want to write a java program to retrieve the status of all the services running on different servers (approx 20). For this i am using SC command, i am able to do so using the java program. But now i am stuck in a situation where i want to run the SC command as a different user by using RUNAS, the problem that i am facing is that i am not able to input the password once the command has been executed for the first time. Following is the code that i am using :-
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/c";
command[2] = "runas /noprofile /user:domain\\admin \"sc \\\\serverName queryex type= service state= all\"";
Process p = Runtime.getRuntime().exec(command);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
new PrintWriter(p.getOutputStream(),true).println("AdminPassword");
System.out.println(line);
line = reader.readLine();
}
BufferedReader stdInput = new BufferedReader(newInputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Input;
while ((Input = stdInput.readLine()) != null) {
System.out.println(Input);
}
String Error;
while ((Error = stdError.readLine()) != null) {
System.out.println(Error);
}
But i am not been able to print the states of all the services. I am not not sure after providing the password whether i need to capture some other stream or else??
Any help on this?
Thanks
In your while (line != null) loop you open a new PrintWriter for each line you read. You print the admin password to these writers, but never close or flush them.
Try the PrintWriter writer you created above, and flush() it after writing the password, otherwise it will still be in the buffer.
You also create several BufferedReader on the inputStream of the Process, which might interfere with each other.
So: create only one reader resp. writer for the inputStream, errorStream and outputStream of the Process.
I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.
You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}
Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer