あなたはコマンドを実行すると、意味のあるメッセージが含まれているerr
出力をキャプチャすることができます。ここで
が、これは仕事ができる方法を示しています(apache commons-execを使用しています)いくつかの最小限の実行可能なコードは次のとおりです。
import org.apache.commons.exec.*;
public static String getErrorMessage(String command) {
CommandLine cmdLine = CommandLine.parse(command);
DefaultExecutor executor = new DefaultExecutor();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
executor.setStreamHandler(new PumpStreamHandler(out, err));
try {
executor.execute(cmdLine);
} catch (Exception e) {
return err.toString().trim();
}
return null; // no error occurred
}
ここでファイル操作エラーの様々な条件を示すこのコードのテストです:
public static void main(String[] args) throws Exception {
System.out.println(getErrorMessage("cp fake.file x"));
System.out.println(getErrorMessage("cp /tmp /tmp"));
System.out.println(getErrorMessage("mkdir /Volumes"));
System.out.println(getErrorMessage("mv /tmp /"));
System.out.println(getErrorMessage("mv fake.file /tmp"));
}
出力(mac osxで実行):
cp: fake.file: No such file or directory
cp: /tmp is a directory (not copied).
mkdir: /Volumes: File exists
mv: /tmp and /tmp are identical
mv: rename fake.file to /tmp/fake.file: No such file or directory
例えば、特定のIOExceptionsに正規表現のマッチングやcontains
を使用して主要なパラメータとマップメッセージのためにそれを解析し、それらを投げることができ、メッセージを得た、ということにIOExceptionをスローする方法では、上記の方法をラップ:
if (message.endsWith("No such file or directory"))
throw new FileNotFoundException(); // Use IOExceptions if you can
if (message.endsWith("are identical"))
throw new IdenticalFileException(); // Create your own Exceptions that extend IOException
あなたの場合これを抽象化して複数のOSのフレーバで使用するには、プラットフォームごとにコードを実装する必要があります(Windowsおよび* nixは、任意のファイル操作/結果に対して異なるシェルコマンド/エラーメッセージを使用します)。
この回答に賞金が授与された場合は、ファイル操作用のスタイリッシュなenum
を含む完全な整然としたバージョンの作業コードを投稿します。
わかりません。しかし、ディレクトリを作成する過程でどのような例外がスローされるのか、なぜそれが失敗するのかを知るためには、ソースコードをチェックすることをお勧めします。 – Moonbeam
@Moonbean:重要な点は、ディレクトリに既に存在する場合のように例外がスローされないことです。 –