Java에서 문서를 여는 더 좋은 방법은 무엇입니까?
문제
저는 다음 코드를 사용하여 Office 문서, PDF 등을 열었습니다.Java를 사용하는 내 Windows 컴퓨터에서는 파일 이름이 "File[SPACE][SPACE]Test.doc"와 같은 여러 연속 공백 내에 포함된 어떤 이유를 제외하고는 잘 작동합니다.
이 작업을 어떻게 수행할 수 있나요?나는 코드 전체를 통조림으로 만드는 것을 싫어하지 않습니다 ...하지만 JNI를 호출하는 타사 라이브러리로 교체하고 싶지 않습니다.
public static void openDocument(String path) throws IOException {
// Make forward slashes backslashes (for windows)
// Double quote any path segments with spaces in them
path = path.replace("/", "\\").replaceAll(
"\\\\([^\\\\\\\\\"]* [^\\\\\\\\\"]*)", "\\\\\\\"$1\"");
String command = "C:\\Windows\\System32\\cmd.exe /c start " + path + "";
Runtime.getRuntime().exec(command);
}
편집하다: 잘못된 파일 창에서 실행하면 파일을 찾는 것에 대해 불평합니다.하지만...명령줄에서 직접 명령줄을 실행하면 정상적으로 실행됩니다.
해결책
Java 6을 사용하는 경우 다음을 사용할 수 있습니다. java.awt.Desktop의 공개 메소드 현재 플랫폼의 기본 애플리케이션을 사용하여 파일을 실행합니다.
다른 팁
이것이 당신에게 많은 도움이 될지 확실하지 않습니다 ...나는 자바 1.5+를 사용한다 프로세스 빌더 Java 프로그램에서 외부 쉘 스크립트를 시작합니다.기본적으로 나는 다음을 수행합니다.(명령 출력을 캡처하고 싶지 않기 때문에 이는 적용되지 않을 수도 있습니다.당신은 실제로 문서를 실행하고 싶어합니다. 하지만 아마도 이것은 당신이 사용할 수 있는 무언가를 촉발시킬 것입니다.)
List<String> command = new ArrayList<String>();
command.add(someExecutable);
command.add(someArguemnt0);
command.add(someArgument1);
command.add(someArgument2);
ProcessBuilder builder = new ProcessBuilder(command);
try {
final Process process = builder.start();
...
} catch (IOException ioe) {}
문제는 파일 이름 구문 분석이 아니라 사용 중인 "시작" 명령일 수 있습니다.예를 들어, 이것은 내 WinXP 시스템(JDK 1.5 사용)에서 잘 작동하는 것 같습니다.
import java.io.IOException;
import java.io.File;
public class test {
public static void openDocument(String path) throws IOException {
path = "\"" + path + "\"";
File f = new File( path );
String command = "C:\\Windows\\System32\\cmd.exe /c " + f.getPath() + "";
Runtime.getRuntime().exec(command);
}
public static void main( String[] argv ) {
test thisApp = new test();
try {
thisApp.openDocument( "c:\\so\\My Doc.doc");
}
catch( IOException e ) {
e.printStackTrace();
}
}
}
제휴하지 않습니다 StackOverflow