• 简单的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(); } } } }
  • 相关阅读:
    关于静态链接库(Lib,.A)与动态链接库(DLL,.SO)
    #pragma once
    动态链接库和静态链接库的区别
    C++编写、生成、调用动态链接库
    cmake 命令行
    Build Slicer application--Compiling and installing Slicer from source
    3DSlicer开发之路——Extensions(九)
    3DSlicer开发之路——Extensions(八)
    3DSlicer开发之路——Extensions(七)
    placeholder文字颜色与是否显示兼容性
  • 原文地址:https://www.cnblogs.com/wxw7blog/p/10430601.html
Copyright © 2020-2023  润新知