![](/img/trans.png)
[英]Android java.io.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.