[Java] java 随机读取文件内容 →→→→→进入此内容的聊天室

来自 , 2019-08-08, 写在 Java, 查看 111 次.
URL http://www.code666.cn/view/996a7fa0
  1.         /**
  2.          * 随机读取文件内容
  3.          *
  4.          * @param fileName
  5.          *            文件名
  6.          */
  7.         public static void readFileByRandomAccess(String fileName) {
  8.                 RandomAccessFile randomFile = null;
  9.                 try {
  10.                         System.out.println("随机读取一段文件内容:");
  11.                         // 打开一个随机访问文件流,按只读方式
  12.                         randomFile = new RandomAccessFile(fileName, "r");
  13.                         // 文件长度,字节数
  14.                         long fileLength = randomFile.length();
  15.                         // 读文件的起始位置
  16.                         int beginIndex = (fileLength > 4) ? 4 : 0;
  17.                         // 将读文件的开始位置移到beginIndex位置。
  18.                         randomFile.seek(beginIndex);
  19.                         byte[] bytes = new byte[10];
  20.                         int byteread = 0;
  21.                         // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
  22.                         // 将一次读取的字节数赋给byteread
  23.                         while ((byteread = randomFile.read(bytes)) != -1) {
  24.                                 System.out.write(bytes, 0, byteread);
  25.                         }
  26.                 } catch (IOException e) {
  27.                         e.printStackTrace();
  28.                 } finally {
  29.                         if (randomFile != null) {
  30.                                 try {
  31.                                         randomFile.close();
  32.                                 } catch (IOException e1) {
  33.                                 }
  34.                         }
  35.                 }
  36.         }

回复 "java 随机读取文件内容"

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

captcha