0

特定の文字列がファイルのリストに含まれているかどうかを知る必要があります。ファイルのリストは動的であり、文字列の動的リストを確認する必要があります。これは、結果(trueまたはfalse)を処理するためにJavaで実行する必要があります。また、MSWindowsも要件です。

私はこれを行うためにUNIXの方法を使用しようとしたその問題について考えました:

find C:/temp | xargs grep import -sl

GnuWinを使用すると、これはcmdで問題なく機能します。だから私はこれをJava言語に変換しようとしました。RuntimeクラスとProcessBuilderクラスの使用に関する多くの記事を読みました。しかし、どのヒントも機能していません。最後に、次の2つのコードスニペットを試しました。

String binDir = "C:/develop/binaries/";

List<String> command = new ArrayList<String>();
command.add("cmd");
command.add("/c");
command.add(binDir+"find");
command.add("|");
command.add(binDir+"xargs");
command.add(binDir+"grep");
command.add("import");
command.add("-sl");

ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("C:/temp"));
final Process proc = builder.start();

printToConsole(proc.getErrorStream());
printToConsole(proc.getInputStream());

int exitVal = proc.waitFor();

String binDir = "C:/develop/binaries/";
String strDir = "C:/temp/";

String[] command = {"cmd.exe ", "/C ", binDir + "find.exe " + strDir + " | " + binDir + "xargs.exe " + binDir + "grep.exe import -sl" };

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);

printToConsole(proc.getErrorStream());
printToConsole(proc.getInputStream());

int exitVal = proc.waitFor();

コマンドを連結する他の多くの方法も試しましたが、エラーメッセージ(ファイルが見つからないなど)が表示されるか、プロセスが返されません。

私の質問:1。この仕事をするためのより良い方法を知っていますか?2.そうでない場合:コードにエラーがありますか?3.そうでない場合:そのコマンドを実行しようとする別の方法はありますか?

前もって感謝します。

4

2 に答える 2

1

頭のてっぺんから:

File yourDir = new File("c:/temp");
File [] files = yourDir.listFiles();
for(File f: files) {
     FileInputStream fis = new FileInputStream(f);
     try {
         BuffereReaded reader = new BufferedReader(new InputStreamReader(fis,"UTF-8")); // Choose correct encoding
         String s;
         while(((s=reader.readLine())!=null) {
             if (s.contains("import"))
              // Do something (add file to a list, for example). Possibly break out the loop
         }
     } finally {
           if (fis!=null)fis.close();
     }
}
于 2012-04-23T14:56:22.320 に答える
1

特にWindowsでは、Javaによるサブプロセスのサポートはかなり弱いです。本当に必要がない場合は、そのAPIの使用を避けてください。

代わりに、このSOの質問findでは、再帰検索のを置き換える方法について説明します。これは、(特に役立つように)grep十分に簡単である必要があります。FileUtil.readLines(…)

于 2012-04-23T15:08:30.737 に答える