简体   繁体   中英

IOException: write failed: EBADF (Bad file number)

i read many posts about EBADF but non of them solved my problem.

so what i am doing is converting.jpg format to bytes and eventually i want to wrtie bytes as binary file.

here is my code.

public static void writeBytes(byte[] bytes,String dstPath){
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;

        try {
            fout = new FileOutputStream(dstPath);
            bout = new BufferedOutputStream(fout);
            bout.write(bytes);

        } catch (IOException io) {
            
        } finally {
            try {

                if (fout != null)
                    fout.close();

                if (bout != null)
                    bout.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

the problem occurs when the bout.write(bytes) is called.

i think i find the problem.

buffer size in (BufferedOutputStream) by default is 8192 and my bytes size was less than it. so i change code like bellow.

public static void writeBytes(byte[] bytes,String dstPath){
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;
        
        int bufferSize = 8192;
        if(bytes.length < bufferSize){
            bufferSize = bytes.length;
        }
        try{
            fout=new FileOutputStream(dstPath);
            bout=new BufferedOutputStream(fout,bufferSize);
            bout.write(bytes);

        }catch (IOException io){
            
        }finally {
            try {
                fout.close();
                bout.close();
            } catch (IOException e) {
             
                e.printStackTrace();
            }
        }
    }

i set the buffer size equals to the size of the bytes by this condition.

 int bufferSize = 8192;
        if(bytes.length < bufferSize){
            bufferSize = bytes.length;
        }

and set buffer size to BufferedOutputStream

bout=new BufferedOutputStream(fout,bufferSize);

i'm not sure this is standard way but is working for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM