zoukankan      html  css  js  c++  java
  • 简单的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(); } } } }
  • 相关阅读:
    Xcode7 真机调试步骤以及遇到的问题解决办法
    AndroidStudio .gitinore编写
    Android Studio Jar、so、library项目依赖
    Android studio导入eclipse项目混淆打包出错
    spring中ref属性与<ref/>标签
    NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.servlet.view.InternalResourceViewResolver' available
    Maven学习笔记
    Tomcat日志与Log4j日志
    Git笔记
    Tomcat学习
  • 原文地址:https://www.cnblogs.com/wxw7blog/p/10430601.html
Copyright © 2011-2022 走看看