改寫的時候,遇到 java.io.IOException: Bad file descriptor 錯誤,
發現是因為InputStream沒有好好處理完就做close()了,

針對緩衝部分還是要注意一下

 

File thisFile= new File("file's src ");

/*
1. use Files.newInputStream() 
Opens a file, returning an input stream to read from the file. 
The stream will not be buffered, and is not required to support the mark or reset methods.
*/
InputStream is = Files.newInputStream(thisFile.toPath());

/*
2. get byte[]
*/
File thisFile= new File("file's src ");
InputStream thisFileIs = null;
try{
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  thisFileIs = new FileInputStream(thisFile);
  byte[] thisFileIsByte = new byte[1024];  
  int len = 0;  
  while ((len = thisFileIs .read(thisFileIsByte )) != -1) {
    outStream.write(thisFileIsByte , 0, len);  
  }  
  byte[] in_b = outStream.toByteArray();
}catch(IOException e){
} finally {  
  if(thisFileIs != null) {  
    try{  
      thisFileIs.close();
    }catch(IOException e) {
    }  
  }  
}

上述等同

InputStream thisFileIs = null;
try{
  thisFileIs = new FileInputStream(thisFile);
  byte[] in_b = IOUtils.toByteArray(new FileInputStream(thisFile));  //這行
}catch(IOException e){
} finally {  
  if(thisFileIs != null) {  
    try{  
      thisFileIs.close();
    }catch(IOException e) {
    }  
  }  
}

 

 

 

 

參考:https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

arrow
arrow
    文章標籤
    java InputStream newInputStream
    全站熱搜

    咪卡恰比 發表在 痞客邦 留言(0) 人氣()