how to run unix commands from java
I want to execute some Unix commands from the java code.
I want to run logcat command from java code.
I am using the below code to do this:
Process p = Runtime.getRuntime().exec("logcat -v time -f /mnt/sdcard/abc.txt");
The above code is working perfectly.
The same way I want to run some other Unix commands .
I want to run "WC -l"(read no.of lines in file) command and I want to store it out put in some integer.
Below is the code that I have written for this:
Process p = Runtime.getRuntime().exec("wc -l /mnt/sdcard/abc.txt");
But it is throwing below exception.
08-19 05:34:53.457 W/System.err( 1269): java.io.IOException: Error running exec(). Command: [wc, -l, /mnt/sdcard/abc.txt] Working Directory: null Environment: null
08-19 05:34:53.457 W/System.err( 1269): at jav开发者_开发知识库a.lang.ProcessManager.exec(ProcessManager.java:224)
08-19 05:34:53.457 W/System.err( 1269): at java.lang.Runtime.exec(Runtime.java:189)
08-19 05:34:53.457 W/System.err( 1269): at java.lang.Runtime.exec(Runtime.java:275)
08-19 05:34:53.457 W/System.err( 1269): at java.lang.Runtime.exec(Runtime.java:210)
Please help me what's the issue in this..
I have a file "abc.txt" in SD card.
is it possible to execute "WC -l" command from java code of android.
If we can execute Unix commands from java code we can make file operations very easier.
Here the list of the System /bin in android there is no "wc" sorry
am check_prereq dexopt fsck_msdos iftop keystore_cli mediaserver netd ps rild service stagefright toolbox
applypatch chmod df gdbjithelper ime kill mkdir netstat qemud rm servicemanager start top
applypatch_static chown dhcpcd gdbserver input linker monkey newfs_msdos qemu-props rmdir setconsole stop umount
app_process cmp dmesg getevent insmod ln mount notify racoon rmmod setprop surfaceflinger updater
audioloop dalvikvm dnsmasq getprop installd log mtpd omx_tests radiooptions route sh svc vdc
bmgr date dumpstate gzip ioctl logcat mv ping reboot run-as showlease sync vmstat
bootanimation dbus-daemon dumpsys hd ionice logwrapper nandread pm record schedtest skia_test system_server vold
bugreport dd dvz id iptables ls ndc pppd recovery schedtop sleep tc watchprops
cat debuggerd flash_image ifconfig keystore lsmod netcfg printenv renice sendevent smd testid3 wipe
wc is not present on android.
dev:~ njzk2$ ./adb shell wc
wc: not found
However, you can consider opening the file and counting the number of lines from there.
You can try grep
instead.
The following command:
$ wc -l filename
outputs the equivalent to:
$ grep -c '.*' filename
The expression .*
means any character except line break zero or more times, which works for lines of every possible size.
Related: https://unix.stackexchange.com/q/25344
PS: You can play with and debug regular expressions at https://regexr.com/
精彩评论