按字节读取文件

1.按字节读取整个文件

Long keyFilelength = keyFile.length();
 byte[] keyBytes = new byte[keyFilelength.intValue()];
  //1.读取密钥文件
  try {
   FileInputStream in = new FileInputStream(keyFile);
   in.read(keyBytes);
   in.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }

2.按照固定字节读取文件

StringBuffer sb = new StringBuffer();

 try {
   // 创建文件输入流对象
   FileInputStream is = new FileInputStream(file.getPath());
   // 设定读取的字节数
   int n = 128;
   byte buffer[] = new byte[n];
   // 读取输入流
   while ((is.read(buffer, 0, n) != -1) && (n > 0)) {
    String rsaDecrypt = new String(buffer, UTF-8");
    sb.append(rsaDecrypt);
   }
   // 关闭输入流
   is.close();
     } catch (FileNotFoundException e) {
      re.setSuccess(false);
   re.setMsg(I18nTool.getText("mainframe.window.cannotFindFile", lang));
     } catch (Exception e) {
   re.setSuccess(false);
   re.setMsg(I18nTool.getText("mainframe.window.decryptFail", lang));
  }

 

你可能感兴趣的:(按字节读取文件)