java中的文件操作

来源:互联网 发布:2016年汽车保险数据 编辑:程序博客网 时间:2024/05/17 03:33

 

随机读取文件中的一部分文字~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/** * 随机读取 *  * @param fileName */public String readFileByRandomAccess(String fileName) {StringBuffer sb = new StringBuffer();RandomAccessFile randomFile = null;try {randomFile = new RandomAccessFile(fileName, "r");int fileLength = (int) randomFile.length();int beginIndex = random.nextInt(fileLength);randomFile.seek(beginIndex);int byteNum = 0;while (byteNum < 1) {byteNum = random.nextInt(10);}byte[] bytes = new byte[byteNum];int byteread = 0;while ((byteread = randomFile.read(bytes)) != -1) {sb.append(new String(bytes, 0, byteread));}} catch (IOException e) {e.printStackTrace();} finally {if (randomFile != null) {try {randomFile.close();} catch (IOException e1) {e1.printStackTrace();}}}return sb.toString();}


原创粉丝点击