Android在文件操作時出現java.io.FileNotFoundException

說不清楚,直接看代碼吧

public class ImageNetService{
 //http://p2.qhimg.com/t0112c0fd8f19123109.jpg
 FileOutputStream fileOutputStream;
 
 public ImageNetService(FileOutputStream fileOutputStream) {
  super();
  this.fileOutputStream = fileOutputStream;                    //不能new FileOutputStream ,而應該openFileOutput("gaoxiao.jpg", this.getContext().MODE_PRIVATE));

 }
 public void getNetImage() throws Throwable{
  String s="http://p2.qhimg.com/t0112c0fd8f19123109.jpg";
  URL url=new URL(s);
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setConnectTimeout(10*1000);
  connection.setRequestMethod("GET");
  if(connection.getResponseCode()!=200){
   throw new RuntimeException("請求URL無響應");
  }
  InputStream inputStream=connection.getInputStream();
  byte[]result=readData(inputStream);
  //File file=new File("gaoxiao.jpg");                          //在javase環境下,是這樣寫的
  //FileOutputStream fileOutputStream=new FileOutputStream(file);//這樣寫在安卓系統中報錯
  fileOutputStream.write(result);
  fileOutputStream.close();
 }
 public static byte[] readData(InputStream inputStream) throws Exception{
  ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  byte[] buffer=new byte[1024];
  int len=-1;
  while((len=inputStream.read(buffer))!=-1){
   outputStream.write(buffer, 0, len);
  }
  byte[]data=outputStream.toByteArray();
  outputStream.close();
  inputStream.close();
  return data;
 }
 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章