怎么通过javaIO流来修改数据。
本地有个文件asd.txt.其内容是
djak
01 233
02 345
03 889
现在我想修改其中02 345 变为01 345 怎么修改。
求助~~~~~~~~~~~~~~~~~~~
本地有个文件asd.txt.其内容是
djak
01 233
02 345
03 889
现在我想修改其中02 345 变为01 345 怎么修改。
求助~~~~~~~~~~~~~~~~~~~
1、Reader方式打开"asd.txt"; 比如:Scanner sc = new Scanner(new File("/xxoo/asd.txt"));
2、Writer方式打开"asd.txt.tmp";
3、循环逐行读取 "asd.txt"; 比如:
while(sc.hasNextLine()) {
String line = sc.nextLine();
4、检查line是否是你要修改的哪行,如果是的就修改它,比如:
line = line.replaceAll("02", "01");
5、将line写入"asd.txt.tmp"
6、循环结束后,关闭这两个文件;
7、删除"asd.txt";
8、将"asd.txt.tmp"重命名为"asd.txt";
FileWriter fw=null;
try {
fr=new FileReader("Det.txt");//源文件要修改的文件
// BufferedReader in=new BufferedReader(fr);
fw=new FileWriter("pid.txt");//缓存文件读入进去
// PrintWriter pw=new PrintWriter(fw);
char[]cbuf=new char[32];
int hasRead = 0;
while ((hasRead=fr.read(cbuf))>0)
{
while(fr.hasNextLine())
{
String Line = fr.NextLine();
if(Line==2) //这个没法比较。修改不了
{Line=Line.replaceAll("02","01");
}
}
fw.write(cbuf,0,hasRead);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
有问题这个。修改不了、、
FileReader 没有 nextLine 好吧好歹看看我3楼写的啊
* Created by IntelliJ IDEA.
* User: gaoyong
* Date: 2012-8-9
* Time: 15:31:42
* To change this template use File | Settings | File Templates.
*/
public class ChangeText { public static void main(String[] args) throws Exception {
FileReader reader=new FileReader("asd.txt");
BufferedReader br=new BufferedReader(reader); FileWriter fw=new FileWriter("asd.txt.tmp");
String s="";
while((s=br.readLine())!=null){
System.out.println(""+s);
//下面的if语句 写自己的替换逻辑
if(s.equals("02 345")){
s="01 345";
}
fw.write(s);
fw.write("\r\n");
fw.flush();
}
br.close();
fw.close();
File renameFile=new File("asd.txt");
renameFile.delete(); //删掉原来的文件
File file=new File("asd.txt.tmp");
file.renameTo(renameFile); // 重命名文件
}
}