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(); } } } }
  • 相关阅读:
    NLTK
    Pytorch tutorials
    LinearRegression
    Pytorch 多分类问题
    Pytorch LogisticRegressionModel BC
    Pytorch LinearModel
    DeepLearningExamples
    Machine Learning Paper
    Hadoop集群nodes unhealthy(yarn 8088)排查及解决办法
    Full Stack Deep Learning
  • 原文地址:https://www.cnblogs.com/wxw7blog/p/10430601.html
Copyright © 2011-2022 走看看