JavaのシンプルなWebDAVクライアントライブラリSardineを使用する。
gradle
implementation 'com.github.lookfirst:sardine:5.10'
なお、5.9以前をJava 9以降で使う場合、明示的にjaxb関連の依存性を追加する必要がある。
compile group: 'com.github.lookfirst', name: 'sardine', version: '5.9'
// https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api
compile group: 'javax.xml.bind', name: 'jaxb-api'
// https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-core
compile group: 'com.sun.xml.bind', name: 'jaxb-core', version: '2.3.0.1'
// https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-impl
compile group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.0.1'
上記のようにしないと以下のようなNoClassDefFoundError
が発生する。これはJava 9でjaxbがデフォルトでは読み込まれなくなったため。
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
at com.github.sardine.impl.SardineImpl.propfind(SardineImpl.java:459)
ちなみに5.10からorg.glassfish.jaxb:jaxb-runtime
の依存性を含むようになっている。
java
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import com.github.sardine.DavResource;
import com.github.sardine.Sardine;
import com.github.sardine.SardineFactory;
public class SardineSample {
public static void main(String[] args) throws IOException {
Sardine sardine = SardineFactory.begin();
//リソース一覧の取得
List<DavResource> resources = sardine.list("http://localhost:81/uploads/");
for (DavResource r : resources) {
System.out.println(r);
}
//ダウンロード
try (InputStream inputStream = sardine.get("http://localhost:81/uploads/asd.txt")) {
Files.copy(inputStream, Paths.get("copy.txt"), StandardCopyOption.REPLACE_EXISTING);
}
//アップロード
sardine.put("http://localhost:81/uploads/asd222.txt", Files.readAllBytes(Paths.get("copy.txt")));
sardine.shutdown();
}
}