簡體   English   中英

IOException: write failed: EBADF (Bad file number)

[英]IOException: write failed: EBADF (Bad file number)

我讀了很多關於 EBADF 的帖子,但沒有一個能解決我的問題。

所以我正在做的是將.jpg格式轉換為字節,最終我想將字節寫為二進制文件。

這是我的代碼。

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();
            }
        }
}

調用 bout.write(bytes) 時會出現問題。

我想我找到了問題所在。

默認情況下(BufferedOutputStream)中的緩沖區大小為8192,我的字節大小小於它。 所以我像下面這樣更改代碼。

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();
            }
        }
    }

在這個條件下,我將緩沖區大小設置為等於字節的大小。

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

並將緩沖區大小設置為 BufferedOutputStream

bout=new BufferedOutputStream(fout,bufferSize);

我不確定這是標准方式,但對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM