简单的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(); } } } }

 

转载于:https://www.cnblogs.com/wxw7blog/p/10430601.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值