????3?????ж?????????
/**
* ???????λ????????????????????е????????
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("???????λ?????????????ζ?????У?");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// ??ζ?????У????????null????????
while ((tempString = reader.readLine()) != null) {
// ????к?
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
????4???????????????
/**
* ?????????????
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("?????????????????");
// ???????????????????????????
randomFile = new RandomAccessFile(fileName?? "r");
// ?????????????
long fileLength = randomFile.length();
// ??????????λ??
int beginIndex = (fileLength > 4) ? 4 : 0;
// ???????????λ?????beginIndexλ?á?
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// ??ζ?10???????????????????10???????????μ?????
// ????ζ?????????????byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes?? 0?? byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}