如何 PrintWriter 在文件的指定位置写数据

navysky 2005-01-04 04:43:16
有一个.txt文件,内容为:
255
512
1024

现在我要用 PrintWriter 方法来改变第二行的数据,如何指定第二行并修改该行的数据???
请指点!
...全文
433 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
navysky 2005-01-05
  • 打赏
  • 举报
回复
首先谢谢大家回复

楼上的  hillMover 谢谢你写了这么多,我调试了一下你写的这段程序:
结果是将第二行的内容删除,PrintWriter 看来不是当前最灵活的选择,其实我也就是想灵活实现对.txt文件内容的修改,如果 RandomAccessFile 能灵活实现的话,那是最好了,我会加分的...
navysky 2005-01-05
  • 打赏
  • 举报
回复
最后用  hillMover(老根) 的方法可以控制行数了,谢谢" hillMover(老根)",谢谢各位...
redex 2005-01-05
  • 打赏
  • 举报
回复
顶.
treeroot 2005-01-05
  • 打赏
  • 举报
回复
或者用两个流
navysky 2005-01-05
  • 打赏
  • 举报
回复
边读边写?是最后的方法了吗?
treeroot 2005-01-05
  • 打赏
  • 举报
回复
说了不行,除非文件是二进制的,不改变大小
你这种情况估计只能一边读一遍写吧
Eraserpro 2005-01-05
  • 打赏
  • 举报
回复
把所有的数据用"\n"分开到数组str,那str[1]就是第二行数据了
navysky 2005-01-05
  • 打赏
  • 举报
回复
现在我用“RandomAccessFile ”改成这样用:
public static void main(String [] args)
{
File saveFilePath = new File("test.txt");
try{RandomAccessFile saveFile = new RandomAccessFile(saveFilePath,"rw");
String con = new String("JAVA test!");
byte [] a = con.getBytes();
saveFile.seek(saveFile.length());
saveFile.write(a);
saveFile.close();
}
catch(Exception e)
{e.printStackTrace();
}
}
但是只能对某个位置进行修改,RandomAccessFile 有没有行的概念?应该怎么写,大伙支持一下...
hillMover 2005-01-04
  • 打赏
  • 举报
回复
import java.io.*;
public class TestIO
{
public static void main(String [] args)
{
try{
File file = new File("data.txt");
if (!file.exists())
{
file.createNewFile();
}
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);


StringBuffer buf = new StringBuffer(br.readLine());
br.readLine();
String temp;
while ((temp=br.readLine())!= null)
{
buf = buf.append( System.getProperty("line.separator"));
buf = buf.append(temp);
}

br.close();

FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();


}catch (IOException e)
{
System.out.println(e);
}
}
}
按你的方法,我做得很笨的!
我写的不好,
因为你如果不说用PrintWriter的话,
我想会有好多办法的!
今天写这个程序,
可能有很大一部分是为了得分吧!
不过这处程序没问题的,
我都试过,前提是你要在这个class文件的同一目录中把你的data.txt文件加入,并写上数据!

fireflyqt 2005-01-04
  • 打赏
  • 举报
回复
使用RandomAccessFile吧
可以的!
javafaq2005 2005-01-04
  • 打赏
  • 举报
回复
非顺序文件
javafaq2005 2005-01-04
  • 打赏
  • 举报
回复
全部读出再全部写入。
tyxsoft 2005-01-04
  • 打赏
  • 举报
回复
2楼的,RandomAccessFile不行????????
treeroot 2005-01-04
  • 打赏
  • 举报
回复
RandomAccessFile好像都不行

62,628

社区成员

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

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