Execute iconv inside java application
I want to convert a big csv file from gb2312 encoding to UTF-8 encoding. Here is the code I used:
Process process = Runtime.getRuntime().exec(
String.format("iconv -c -f %1$s -t %2$s %3$s > %4$s",
sourceEncoding, targetEncoding, source, target));
process.waitFor();
The problem is the proccess.waitFor() method never ends. It looks like the iconv is waiting my input like call it from command line and give no args. But from another session of the terminal. I can see the iconv running with correct parameters开发者_运维百科.
root 16729 0.0 0.1 164076 812 pts/0 S+ 23:00 0:00 iconv -c -f gb2312 -t utf-8 20110525.csv > 20110525.utf8.csv
The command "iconv -c -f gb2312 -t utf-8 20110525.csv > 20110525.utf8.csv" works correctly if I enter it manually from the terminal. But it doesn't work if I call it from java.
The start directory of two way I call the iconv have the same start directory.
As MByD said, the redirection sign is a shell feature.
However, instead of grabbing the OutputStream you could instead execute bash from Java:
... .exec("bash -c 'iconv -c -f gb2312 -t utf-8 20110525.csv > 20110525.utf8.csv'")
The redirection sign (>
) is shell/cmd feature, not java, you cannot use it when executing a process from java.
You can grab the OutputStream of the process (InputStream is = process.getInputStream()
) and save it to file.
精彩评论