This question already has answers here:
How to execute cmd commands via Java
(11 answers)
Closed 9 years ago.
I want to set output stream to the Command prompt like this:
Process p = Runtime.getRuntime()
.exec("C:\\Windows\\System32\\cmd.exe /c start cls");
System.setOut(new PrintStream(p.getOutputStream()));
but it is not working, why ?
By default, PrintStreams will not flush contents written to them automatically. This means that data you write to it will not be immediately sent to the stream it wraps around. However, if you construct the PrintStream using new PrintStream(p.getOutputStream(), true), it will automatically flush when any of the println methods are invoked, a byte array is written or a newline is written. This way, anything you write to it will be immediately accessible to the process.
See http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html
Related
This question already has answers here:
How do I pass parameters to a jar file at the time of execution?
(5 answers)
Closed 4 years ago.
How can we pass a batch variable as parameter to a Java class main method using command line? I want to pass the contents of a text file as an argument to a Java class using command line. for eg : Java -jar TestJar.jar %BATCH_VAR%
I have tried the below code and it doesnt seem to work :
echo "starting"
echo off
set keyvalue=^&Type TestDoc.txt
echo %keyvalue% /// This is printing the right value.
pause
java -jar ErrorUpdate.jar "%keyvalue%" //// This does not pass anything to the Java class :(
pause
I suspect that you may have a misconception about what value is stored in your variable. So let me clarify exactly what is going on in your batch file.
set keyvalue=^&Type TestDoc.txt
echo %keyvalue% /// This is printing the right value.
That is not printing the right value. What you have done is assigned the value &Type TestDoc.txt to the variable. When you then type echo %keyvalue%, this line gets expanded to the following line:
echo &Type TestDoc.txt
This is actually two separate commands. The first, echo, simply queries if the echo setting is currently on or off. The second command, Type TestDoc.txt, is then executed.
At no point does the variable keyvalue ever contain the contents of the file.
So when you have this line in your batch:
java -jar ErrorUpdate.jar "%keyvalue%"
It gets expanded to:
java -jar ErrorUpdate.jar "&Type TestDoc.txt"
This time, the & is enclosed in quotes, so it does not act as a statement separator, but instead is passed to your java class's main method. Your main method just sees the string "&Type TestDoc.txt" passed in as args[0].
If you want the java application to receive the full contents of the file, you need to make your java application read the contents itself.
This question already has answers here:
Inserting text into an existing file via Java
(8 answers)
Closed 6 years ago.
In my project, we are writing a file using DataOutputStream. We are writing different data types like short, byte, int and long and we are using respective methods in DataOutputStream like writeShort(), writeByte() etc.
Now, I want to edit one record in this file at a particular offset. I know the offset from which that record starts but I am not sure what is the right approach of writing to the file because only method in DataOutputStream supporting offset is the one which takes byte[].
I want to write the whole record which is a combination of different data types as mentioned above.
Can someone please tell me what is the correct approach for this?
In your case, you should use RandomAccessFile in order to read and/or write some content in a file at a given location thanks to its method seek(long pos).
For example:
try (RandomAccessFile raf = new RandomAccessFile(filePath, "rw")) {
raf.seek(offset);
// do something here
}
NB: The methods writeShort(), writeByte() etc. and their read counterparts are directly available from the class RandomAccessFile so using it alone is enough.
I have the code below:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['java', '-jar', 'action.jar'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
stdout1, stderr1 = p.communicate(input=sample_input1)
print "Result is", stdout1
p = Popen(['java', '-jar', 'action.jar'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
stdout2, stderr2 = p.communicate(input=sample_input2)
print "Result is", stdout2
Loading the jar takes a lot of time and is very inefficient. Is there any way to avoid reloading it the second time, in the second line p = Popen(...), i.e. just loading it once in the beginning and continue using that instance? I tried to remove the second line unsuccessfully, Python complains:
"ValueError: I/O operation on closed file".
Is there any solution to this? Thanks!
communicate() waits for the process to terminate, so that explains the error you're getting -- the second time you call it, the process isn't running any more.
It really depends on how that JAR was written, and the kind of input it expects. If it supports executing its action more than once based on input, and if you can reformat your input that way, then it would work. If the JAR does its thing once and terminates, there's not much you can do.
If you don't mind writing a bit of Java, you can add a wrapper around the classes in action.jar that takes both your sample inputs in turn and passes them to the code in the jar.
You can save on the cost of starting up the Java Virtual Machine, using a tool like Nailgun.
This question already has answers here:
Print java output to a file
(5 answers)
Closed 9 years ago.
My question is related to this one. However, I am looking for a way to append the text file over several runs. is there a way to write console output to a text file without erasing the old runs information? I am working on 30+ classes and it would be tedious to change System.out.println statements so I prefer sticking with the System.setOut solution.
I have the following code based on #Mac answer
PrintStream out = new PrintStream(new FileOutputStream("aa.txt"),true);
System.setOut(out);
but the file aa.txtdoes not append the results, am I missing something here?
When you create a FileWriter or FileOutputStream for your file, pass true as a second argument to the constructor of the FileWriter or FileOutputStream.
FileWriter(File file, boolean append)
FileWriter and FileOutputStream provide a constructor with an append flag. Just modify the referenced code accordingly
You should use:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"),true);
System.setOut(out);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Print java output to a file
In a Java program, I have a long method, (which I don't think is important to post since it's not vital to the question) that has a large number of println statements to print status updates to the console.
Instead of having these printout to the console, I'd like them to go into a txt file where I can store them and review them later.
Is there a simple way to redirect the output without manually going through each println statement?
If not, what's the best way to go about this?
I have had to do this before, it isn't very neat and I hope you aren't doing it for a final piece of code, but I did:
PrintStream ps = new PrintStream("\file.txt");
PrintStream orig = System.out;
System.setOut(ps);
//TODO: stuff with System.out.println("some output");
System.setOut(orig);
ps.close();
The System class has a static method, System.setOut(PrintStream out). All you have to do is create your own PrintStream that writes to a file, stuff it into this method and you're all set.
Better less fragile solution: Don't use System.out.printFoo(...) but instead just use a logger, and change the logging levels as it suits your purposes at that time.
add extra parameter to the method , PrintStream out
search&replace System.out with out in your method.
done.
(call method with a PrintStream wrapped around a FileOutputStream)