读取文本文件并回写数据怎么实现?

干饭人之路 2009-09-17 10:00:52
我知道读取文件可以这样:

import java.io.*;

public class ReadFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader myFileReader=new FileReader("d:/javatest/dsstatic_20090427.f");

BufferedReader myBufferedReader=new BufferedReader(myFileReader);


String myString=null;

String resultString=new String();

while((myString=myBufferedReader.readLine())!=null)
{ System.out.println(myString);
}
myFileReader.close();

}
}

但是要实现对某一特定行回写数据应该怎么做?
比如,发现myString中有txt字符串,把这个字符串改写为txt123,并回写到那一行,代码应该怎么写?
...全文
153 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
EM265 2009-09-18
  • 打赏
  • 举报
回复

public static void main(String[] args) throws Exception{
//如果a.txt文件中包函 txt 则会把 txt 替换成txt123 ,楼主可试试,看是不是你所想要的那种
String filePath = "c:/tmp/a.txt";
String tmpFile = "c:/tmp/"+System.currentTimeMillis()+".txt";
copyFile(filePath,tmpFile);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tmpFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] b = new byte[1024];
int c =0;
while((c=bis.read(b)) > 0){
String s = new String(b).replaceAll("txt", "txt123");
bos.write(s.getBytes());
}
bis.close();
bos.close();
//删除临时文件
new File(tmpFile).delete();
}

/**复制文件*/
private static void copyFile(String sourceFile,String targetFile)throws Exception{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] by = new byte[1024];
int c=0;
while((c = bis.read(by))> 0){
bos.write(by);
}
bos.close();
bis.close();
}
dajiadebeibei9 2009-09-17
  • 打赏
  • 举报
回复
你用的BufferedReader写入 对应的应该是BufferedWriter
可以这样初始化 BufferedWriter bw = new BufferedWriter(new FileWriter("输出文件路径"));
如果发现字符串里面有txt 可以用repalceAll()方法
具体是这样的:StringBuffer sb = new StringBuffer("要传入的字符串");
sb = sb.replaceAll("txt","txt123");
ruisheng_412 2009-09-17
  • 打赏
  • 举报
回复
FileReader 对应Filewrite

BufferedReader 对应 BufferedWrite
gutan_fox 2009-09-17
  • 打赏
  • 举报
回复
等待~
bayougeng 2009-09-17
  • 打赏
  • 举报
回复
用RandomAccessFile可以实现。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧