◆ソース(必要に応じてtry-catchを入れること。でないとexception発生時にexceptionがブラウザに出てしまう。)
package sample.niocopy;
import java.io.BufferedOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
public class MyServlet extends HttpServlet {
public static void main(String[] args) throws Exception {
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(MyServlet.class, "/*");
Server server = new Server(8090);
server.setHandler(handler);
server.start();
server.join();
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {
try {
Path uri = Paths.get("c:/tmp" + req.getRequestURI());
if (Files.notExists(uri) || Files.isDirectory(uri)) {
res.setStatus(404);
} else {
res.setContentType("application/octet-stream");
res.setContentType("text/html; charset=UTF-8");
res.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", uri.getFileName()));
try (BufferedOutputStream bos = new BufferedOutputStream(res.getOutputStream())) {
Files.copy(uri, bos);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
◆速度
◆結論
普通に使える。パット見メモリリークはないが、要確認。BufferedOutputStream,BufferedInputStreamの2つを利用した場合と比較したが、速度は同じ。
◆pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sample</groupId>
<artifactId>NioCopy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>NioCopy</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty.version>9.3.6.v20151106</jetty.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty.version}</version>
</dependency>
</dependencies>
</project>
- 速度確認した仮想マシン
- CPU core数:4
- メモリ:2.5GB
- OS:Windows10 Pro x64
- 仮想マシン:VMWare vShpere ESXi6.5
- Java:1.8
- ホストPCの性能(参考)
- CPU:Intel Core i5-4250U(2Core 2HT)
- メモリ:16GB
- ドライブ:SSD(ウルトラ II mSATA SSD SDMSATA-512G-G25C)
- 仮想マシン:VMWare ESXi6.5上の仮想マシン

0 件のコメント:
コメントを投稿