import java.io.*; |
/* |
* RandomFile.java |
* |
* Created on 2006年8月22日, 下午9:47 |
* |
* 文件随机访问 |
*/ |
public class RandomFile { |
/* |
* 文件随机访问的方法 |
* |
* void seek(long pos); 将文件指针移动到参数指定的位置。 long getFilePointer(); 得到当前文件指针的位置。 |
* int skipBytes(int n); 将文件指针向前移动参数指定的n个字节。 String readLine(); |
* 从当前文件指定位置读取一行。 |
*/ |
public static void main(String[] args) { |
String tempStr; |
int fileLines = 0 ; |
long pointerLast = 0 ; |
try { |
RandomAccessFile inObj = new RandomAccessFile( |
"d:\\mydir\\secondFile.txt" , "rw" ); |
while (inObj.readLine() != null ) |
fileLines++; |
for ( int i = 0 ; i < fileLines / 2 ; i++) { |
inObj.seek( 2 * i); |
tempStr = inObj.readLine(); |
System.out.println(tempStr); |
} |
pointerLast = inObj.getFilePointer(); |
} catch (IOException e) { |
e.printStackTrace(); |
} |
try { |
RandomAccessFile fileObj = new RandomAccessFile( |
"d:\\mydir\\secondFile.txt" , "rw" ); |
String writeStr = new String( "Insert a string!" ); |
fileObj.seek(pointerLast); |
fileObj.writeChars(writeStr); |
} catch (IOException e) { |
e.printStackTrace(); |
} |
} |
} |