स्व-निहित पद्धति बनाने के लिए @ टिम के उदाहरण पर निर्माण:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Shell {
/** Returns null if it failed for some reason.
*/
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);
//There should really be a timeout here.
if (0 != process.waitFor())
return null;
return output;
} catch (Exception e) {
//Warning: doing this is no good in high quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
public static void main(String[] args) {
test("which bash");
test("find . -type f -printf '%T@\\\\t%p\\\\n' "
+ "| sort -n | cut -f 2- | "
+ "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");
}
static void test(String cmdline) {
ArrayList<String> output = command(cmdline, ".");
if (null == output)
System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
else
for (String line : output)
System.out.println(line);
}
}
(परीक्षण उदाहरण एक कमांड है जो सभी फाइलों को एक निर्देशिका और इसके उपनिर्देशिका में, पुनरावर्ती, कालानुक्रमिक क्रम में सूचीबद्ध करता है ।)
वैसे, अगर कोई मुझे बता सकता है कि मुझे दो और चार के बजाय चार और आठ बैकस्लैम की आवश्यकता क्यों है, तो मैं कुछ सीख सकता हूं। मैं जो गिन रहा हूं, उसकी तुलना में अनसेफ होने का एक और स्तर है।
संपादित करें: बस लिनक्स पर इसी कोड की कोशिश की, और वहाँ यह पता चला है कि मुझे टेस्ट कमांड में कई बैकस्लैम के रूप में आधे की आवश्यकता है! (यह है: दो और चार की अपेक्षित संख्या।) अब यह सिर्फ अजीब नहीं है, यह एक पोर्टेबिलिटी समस्या है।
catऔरcshएक दूसरे के साथ करने के लिए कुछ भी नहीं है।