In the actual project, Java sometimes needs to call C write out of things, in addition to JNI, I think a better way is Java call the shell. First write the C to make the executable file, and then write a shell script to execute the executable file, and finally Java calls the shell script.
The Java invocation is simple, with the following examples:
The first is the shell script
[Plain]View plain copy print?
- #!/bin/sh
- echo Begin Word cluster
- /home/felven/word2vec/word2vec-train/home/felven/word2vec/resultbig.txt-output/home/felven/word2vec/ Classes.csv-cbow 0-size 200-window 5-negative 0-hs 1-sample 1e-3-threads 12-classes 2000
- echo the word classes were saved to file Classes.csv
Then the Java calling code
[Java]View plain copy print?
- Import Java.io.BufferedReader;
- Import Java.io.InputStreamReader;
- Public class Runshell {
- public static void Main (string[] args) {
- try {
- String shpath="/home/felven/word2vec/demo-classes.sh";
- Process PS = Runtime.getruntime (). exec (Shpath);
- Ps.waitfor ();
- BufferedReader br = new BufferedReader (new InputStreamReader (Ps.getinputstream ()));
- StringBuffer sb = new StringBuffer ();
- String Line;
- While (line = Br.readline ()) = null) {
- Sb.append (line) append ("\ n");
- }
- String result = Sb.tostring ();
- SYSTEM.OUT.PRINTLN (result);
- }
- catch (Exception e) {
- E.printstacktrace ();
- }
- }
- }
It is actually a process class that makes the call and then outputs the shell execution results to the console.
It is important to note that the WAITFOR () function needs to be executed at invocation, because the shell process is a child of the Java process, and Java as the parent process needs to wait for the child process to finish executing.
In addition to the Eclipse console output is not the side of the execution side output, but the shell after the completion of all the output, so if the more complex shell script to see no output may be mistaken for execution, this time to look at the terminal process, With the top command you can see that the shell script has actually started executing.
Java invoke shell script