这是我下载文件的简单代码:

InputStream input = null;
        OutputStream output = null;
        try {
            URL fileURL = new URL(f.getVideoURL());
            URLConnection con = fileURL.openConnection();
            lengthOfContent = con.getContentLength();
            con.setConnectTimeout(10 * 1000);
            con.connect();

            input = new BufferedInputStream(fileURL.openStream());
            File f = new File("/sdcard/",fileName);
            if(!f.exists()){
                f.createNewFile();
            }else{
                f.delete();
                f.createNewFile();
            }
            output = new FileOutputStream(f);

            Log.v("FILE", fileName);

            byte[] data = new byte[2 * 1024];
            long tempBytesWritten = 0;


            while((tempBytesWritten=input.read(data))!=-1){
                bytesWritten.addAndGet(tempBytesWritten);
                output.write(data,0,(int)tempBytesWritten);
                synchronized(h){
                    h.post(new Runnable(){
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
                output.flush();
                output.close();
                input.close();
            }


尽管我使用con.connect()连接,但它说BufferedInputStream没有打开。
我如何确保它是打开的?

08-06 19:45:12.070: W/System.err(9244): java.io.IOException: BufferedInputStream is closed
08-06 19:45:12.070: W/System.err(9244):     at java.io.BufferedInputStream.streamClosed(BufferedInputStream.java:118)
08-06 19:45:12.075: W/System.err(9244):     at java.io.BufferedInputStream.read(BufferedInputStream.java:271)
08-06 19:45:12.075: W/System.err(9244):     at java.io.InputStream.read(InputStream.java:163)
08-06 19:45:12.075: W/System.err(9244):     at com.example.tqafragments.Task.run(Task.java:67)
08-06 19:45:12.080: W/System.err(9244):     at java.lang.Thread.run(Thread.java:856)

最佳答案

什么是互联的?

您是否尝试过以这种方式打开流?

//remove con.connect();
input = new BufferedInputStream(con.getInputStream());

关于android - IOException下载文件时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18082371/

10-14 11:38