简单的NIO使用实例

public class ThreadTest_2 {
    public static void main(String[] args) {
        Thread downloaderThread = null;
        for (String url : args) {
            downloaderThread = new Thread(new FileDownload(url));
            downloaderThread.start();
        }
    }

    static class FileDownload implements Runnable {

        private final String fileURL;

        public FileDownload(String fileURL) {
            this.fileURL = fileURL;
        }

        @Override
        public void run() {
            System.out.println("Downloading from " + fileURL);
            String fileBaseName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
            try {
                URL url = new URL(fileURL);
                String localFileNmae = "D:\\viscent-" + fileBaseName;
                System.out.println("Saving to " + localFileNmae);
                downloadFile(url, new FileOutputStream(localFileNmae), 1024);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Done downloading from " + fileURL);
        }

        private void downloadFile(URL url, FileOutputStream fileOutputStream, int bufSize) throws Exception {
            final HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            int resonseCode = httpURLConnection.getResponseCode();
//读通道 ReadableByteChannel inChannel
= null;
//写通道 WritableByteChannel outChannel
= null; try { if (2 != resonseCode / 100) { throw new IOException("Eroor: HTTP" + resonseCode); } if (0 == httpURLConnection.getContentLength()) { System.out.println("没有内容可下载"); } inChannel = Channels.newChannel(new BufferedInputStream(httpURLConnection.getInputStream())); outChannel = Channels.newChannel(new BufferedOutputStream(fileOutputStream)); ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize); while (-1 != inChannel.read(byteBuffer)) {
//反转状态,由写变读 byteBuffer.flip(); outChannel.write(byteBuffer); byteBuffer.clear(); } }
finally { inChannel.close(); outChannel.close(); httpURLConnection.disconnect(); } } } }

 

posted @ 2019-02-25 14:07  竹马今安在  阅读(1130)  评论(0编辑  收藏  举报