说不清楚,直接看代码吧

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

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐