2012-04-23 5 views
0

특정 문자열이 파일 목록에 포함되어 있는지 알아야합니다. 파일 목록은 동적이며 문자열의 동적 목록을 확인해야합니다. 결과를 처리하려면 Java에서 수행해야합니다 (true 또는 false). 그리고 MS Windows도 필요합니다.Java에서 GnuWin 명령을 호출하거나 더 좋은 방법이 있습니까?

find C:/temp | xargs grep import -sl 

GnuWin은이 아무 문제없이 cmd를 작동합니다

나는 내가이 일을 유닉스 방법을 사용하려고 그 문제에 대해 생각했다. 그래서 이것을 자바 언어로 변환하려고했습니다. Runtime 클래스와 ProcessBuilder 클래스 사용에 관한 많은 기사를 읽었습니다. 그러나 팁 중 어느 것도 작동하지 않습니다.

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(); 

나는 또한 명령을 CONCAT 많은 다른 방법을 시도

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(); 

하지만 중 I (예 :이 파일을 찾을 수 없습니다.) 오류 메시지가 : 마지막으로 나는 다음과 같은 두 가지 코드 조각을 시도 또는 과정이 결코 돌아 오지 않습니다.

내 질문 : 1.이 직업을하기에 더 좋은 방법이 있습니까? 2. 그렇지 않은 경우 : 코드에 오류가 있습니까? 3. 그렇지 않은 경우 : 해당 명령을 실행해야하는 다른 방법이 있습니까?

미리 감사드립니다. 내 머리의 상단에서

+0

첫 번째 시도에서 strDir이 표시되지 않습니다. 오타입니까? –

+0

아니요, 두 번째의 strDir은 첫 번째 파일에서'builder.directory (새 파일 ("C :/temp"));로 설정됩니다. –

+1

strDir과 binDir을 혼동하지 않으십니까? 어쨌든, personnally 나는 오히려 자바 코드와 필요하다면 당신의 cmd와 같은 자바 라이브러리/프레임 워크를 사용해 보려고합니다. 유닉스가 권력을 장악하는 것을 좋아하지만, 작성한 코드는 그다지 강력하지도 않고 휴대하기도 쉽지 않습니다. –

답변

1

자바의 지원은 특히 Windows에서 꽤 약하다. 실제로 ~이 필요하지 않으면 해당 API를 사용하지 마십시오.

대신 this SO question는 (도움을 특히 FileUtil.readLines(…)와) 재귀 검색에 대한 find를 교체하고 grep 충분히 쉽게하는 방법에 대해 설명합니다.

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(); 
    } 
} 
+0

POSIX'find'는 기본적으로 재귀 적이라는 것을 알고 있습니까? –

+0

@DonalFellows 예 :-)이 코드는 내가 이것을 할 수있는 방법을 설명하기위한 작은 코드 일뿐입니다. 나는 재귀 적 방법을 사용하는 것이 그렇게 어렵지 않다고 생각한다. –

관련 문제