精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-04-05
转自 开发者的天空
随机访问文件
允许我们不按照顺序的访问文件的内容,这
里的访问包括读和写。要随机的访问文件,我们就要打开文件,定位到指定的位置,然后读或写文件内容。在Javs SE
7中,SeekableByteChannel接口提供了这个功能。 import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; String s = "I was here!\n"; byte data[] = s.getBytes(); ByteBuffer out = ByteBuffer.wrap(data); ByteBuffer copy = ByteBuffer.allocate(12); FileChannel fc = null; Path file = Paths.get("c:\\testChannel.txt"); try { fc = (FileChannel)file.newByteChannel(StandardOpenOption.READ, StandardOpenOption.WRITE); //Read the first 12 bytes of the file. int nread; do { nread = fc.read(copy); } while (nread != -1 && copy.hasRemaining()); //Write "I was here!" at the beginning of the file. fc.position(0); while (out.hasRemaining()) fc.write(out); out.rewind(); /*Move to the end of the file, write "I was here!" again,then copy the first 12 bytes to the end of the file.*/ long length = fc.size(); fc.position(length); while (out.hasRemaining()) fc.write(out); copy.flip(); while (copy.hasRemaining()) fc.write(copy); } catch (IOException x) { System.out.println("I/O Exception: " + x); } finally { //Close the file. if (fc != null) fc.close(); System.out.println(file + " has been modified!"); } 假设原来的文件内容为 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
浏览 1995 次