A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 何羡玉 中级黑马   /  2013-5-14 19:19  /  1412 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 何羡玉 于 2013-5-15 10:38 编辑

我在“好好学习”后插入day day up  ,想要的打印结果是 “好好学习 day day up 天天向上” 但是我这个代码执行后的结果是 “好好学习 day day up”   把原来的天天向上覆盖了。为什么啊  怎么样才能不覆盖、
package enhanceTest;

import java.io.*;

public class Access {

        public void writerFile() throws IOException
        {
                RandomAccessFile ran=new RandomAccessFile("e:\\cccccc.txt", "rw");
                ran.write("好好学习 天天向上".getBytes());
         ran.seek(8);
                ran.write("day day up".getBytes());
                ran.close();        
        }
        public void readFile() throws IOException
        {
                RandomAccessFile ran=new RandomAccessFile("e:\\cccccc.txt", "r");
                byte[] b=new byte[100];
                int len=ran.read(b);
                String s=new String(b,0,len);
                System.out.println(s);        
                 ran.close();        
        }
        public static void main(String[] args) throws IOException {
               
                Access acc=new  Access();
                acc.writerFile();        
                acc.readFile();
        }
}

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

2 个回复

倒序浏览
你好,据我观察发现,当通过seek后再写入数据时 只是把原文件中插入点后面的数据进行了修改,不能实现你想要的插入效果。
我改了改你的代码,希望能帮到你
  1.          public static void writerFile() throws IOException
  2.         {
  3.                         //输出流
  4.                 RandomAccessFile ran=new RandomAccessFile("1.txt", "rw");
  5.                 ran.write("好好学习天天向上".getBytes());
  6.                                 //输入流
  7.                                 RandomAccessFile ran1=new RandomAccessFile("1.txt", "r");
  8.                                 //获取文件长度
  9.                                 int length=(int)ran1.length();
  10.                 byte[]buf=new byte[length];
  11.                                 //写入数组
  12.                                 ran1.read(buf);
  13.                                 //获取插入点后面的字符串
  14.                                 String lefttext=new String(buf,8,length-8);
  15.                                  ran.seek(8);
  16.                 String newtxt="day day UP";
  17.                                 byte[]buf1=newtxt.getBytes();
  18.                                 int len1=buf1.length;
  19.                 ran.write(buf1);
  20.                                 //获得新的插入点
  21.                                 ran.seek(8+len1);
  22.                                 //写入原来数据
  23.                                 ran.write(lefttext.getBytes());
  24.                                 ran.close();
  25.                 ran1.close();      
  26.         }
复制代码

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马