Java判断文件是否完整

来源:互联网 发布:淘宝导航条怎么做 编辑:程序博客网 时间:2024/05/18 10:47

需求:需要判断一个文件是否正常结束,正常情况最后一行为某段字符串(结束标志)


代码:

/**       * 判断一个文件的最后一行是否为某字符串       *       * @param src       *            文件路径       * @param key       *            判断是否最后一行的字符串       *     是 则 返回 true 不是 则 返回 false       */       public static boolean checkLastLine(String src, String key) {             int c;            String line; // 读取新文件            RandomAccessFile rf = null;             boolean isEnd = false;             try {                  rf = new RandomAccessFile(src, "r" );                   long len = rf.length();                   long start = rf.getFilePointer();                   long nextend = start + len - 1;                  rf.seek(start + len - 1);                   while(nextend > start) {                        c = rf.read();                        line = rf.readLine();                         //判断读到的最后一行                         if ((c == '\n' || c == '\r')&& line!=null&&!line.equals("" ) ) {                                         if (line.equals(key)) {                                    isEnd = true;                                         }                               break;                        }                        nextend--;                        rf.seek(nextend);                  }            } catch (FileNotFoundException e) {                  e.printStackTrace();            } catch (IOException e) {                  e.printStackTrace();            } finally {                   try {                        rf.close();                  } catch (IOException e) {                        e.printStackTrace();                  }            }             return isEnd;      }


部分代码片段截取自网络,根据实际开发需求修改并抽取出来的方法。