随机读取文件中的一部分文字~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* 随机读取
*
* @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();
}