下载文件时出现IOException

时间:2013-08-06 14:01:36

标签: android

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

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)

2 个答案:

答案 0 :(得分:2)

什么是con.connected?

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

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

答案 1 :(得分:1)

如果我没错,你就把input.close()放在了......