8、(知识篇)IO流(5)

来源:互联网 发布:最小单片机 编辑:程序博客网 时间:2024/06/05 19:16
public class Test {public static void main(String[] args) throws IOException {// 文件的简单读写// 在指定位置写入数据,但是会替换原有数据// testRandomAccessFile();// 不替换原有数据的思路// 先读取剩余部分,然后在写回来testWriteComplateFile();}public static void testRandomAccessFile() throws UnsupportedEncodingException, IOException {// 后面的参数有// 1、r只读 2、rw读写RandomAccessFile raf = new RandomAccessFile("D:\\Hello.txt", "rw");// 从第二个字符读起raf.seek(2);String str = null;while ((str = raf.readLine()) != null) {System.out.println(new String(str.getBytes("ISO-8859-1"), "GBK"));}// 在指定的位置去写入数据(不过会替换数据)// 如果不指定,则在末尾写raf.seek(10);raf.write("测试一下".getBytes());raf.close();}public static void testWriteComplateFile() throws IOException {// 后面的参数有// 1、r只读 2、rw读写RandomAccessFile raf = new RandomAccessFile("D:\\Hello.txt", "rw");//如果文件比较大,建议先写到硬盘里byte[] buffer = new byte[(int) (raf.length()-10)];//先读取10字节raf.read(buffer,0, 10);//再读取剩余部分,等下将剩余部分再补充回来raf.read(buffer,0, (int) (raf.length()-10));raf.seek(10);raf.write("测试一下".getBytes());//关键代码,将剩余部分补上,就不会覆盖原来的内容了raf.write(buffer);raf.close();}}

0 0
原创粉丝点击