[Java] 以字节为单位读取文件(常用于读二进制文件,如图片、声音、影像等文件) →→→→→进入此内容的聊天室

来自 , 2021-03-09, 写在 Java, 查看 146 次.
URL http://www.code666.cn/view/c361bc7b
  1.         /**
  2.          * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
  3.          *
  4.          * @param fileName
  5.          *            文件的名
  6.          */
  7.         public static void readFileByBytes(String fileName) {
  8.                 File file = new File(fileName);
  9.                 InputStream in = null;
  10.                 try {
  11.                         System.out.println("以字节为单位读取文件内容,一次读一个字节:");
  12.                         // 一次读一个字节
  13.                         in = new FileInputStream(file);
  14.                         int tempbyte;
  15.                         while ((tempbyte = in.read()) != -1) {
  16.                                 System.out.write(tempbyte);
  17.                         }
  18.                         in.close();
  19.                 } catch (IOException e) {
  20.                         e.printStackTrace();
  21.                         return;
  22.                 }
  23.                 try {
  24.                         System.out.println("以字节为单位读取文件内容,一次读多个字节:");
  25.                         // 一次读多个字节
  26.                         byte[] tempbytes = new byte[100];
  27.                         int byteread = 0;
  28.                         in = new FileInputStream(fileName);
  29.                         ReadFromFile.showAvailableBytes(in);
  30.                         // 读入多个字节到字节数组中,byteread为一次读入的字节数
  31.                         while ((byteread = in.read(tempbytes)) != -1) {
  32.                                 System.out.write(tempbytes, 0, byteread);
  33.                         }
  34.                 } catch (Exception e1) {
  35.                         e1.printStackTrace();
  36.                 } finally {
  37.                         if (in != null) {
  38.                                 try {
  39.                                         in.close();
  40.                                 } catch (IOException e1) {
  41.                                 }
  42.                         }
  43.                 }
  44.         }
  45.  
  46.  
  47.  
  48.         /**
  49.          * 显示输入流中还剩的字节数
  50.          *
  51.          * @param in
  52.          */
  53.         private static void showAvailableBytes(InputStream in) {
  54.                 try {
  55.                         System.out.println("当前字节输入流中的字节数为:" + in.available());
  56.                 } catch (IOException e) {
  57.                         e.printStackTrace();
  58.                 }
  59.         }

回复 "以字节为单位读取文件(常用于读二进制文件,如图片、声音、影像等文件)"

这儿你可以回复上面这条便签

captcha