黑马程序员技术交流社区
标题:
RandomAccessFile题目
[打印本页]
作者:
何羡玉
时间:
2013-5-14 19:19
标题:
RandomAccessFile题目
本帖最后由 何羡玉 于 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();
}
}
作者:
乎¤_¤乎
时间:
2013-5-14 20:36
你好,据我观察发现,当通过seek后再写入数据时 只是把原文件中插入点后面的数据进行了修改,不能实现你想要的插入效果。
我改了改你的代码,希望能帮到你
public static void writerFile() throws IOException
{
//输出流
RandomAccessFile ran=new RandomAccessFile("1.txt", "rw");
ran.write("好好学习天天向上".getBytes());
//输入流
RandomAccessFile ran1=new RandomAccessFile("1.txt", "r");
//获取文件长度
int length=(int)ran1.length();
byte[]buf=new byte[length];
//写入数组
ran1.read(buf);
//获取插入点后面的字符串
String lefttext=new String(buf,8,length-8);
ran.seek(8);
String newtxt="day day UP";
byte[]buf1=newtxt.getBytes();
int len1=buf1.length;
ran.write(buf1);
//获得新的插入点
ran.seek(8+len1);
//写入原来数据
ran.write(lefttext.getBytes());
ran.close();
ran1.close();
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2