2012-01-31 61 views
0

我有一个文本文件,其中包含数据库表数据,并试图删除表的一部分。这是该文件中:基本的java I/O文本替换,没有得到预期的输出

name= john 
name= bill 
name= tom 
name= bob 
name= mike 

这里是编译和运行我的Java代码,但输出是不是我所期待和坚持。

import java.io.*; 
public class FileUtil { 

    public static void main(String args[]) { 

     try { 

      FileInputStream fStream = new FileInputStream("\\test.txt"); 
      BufferedReader in = new BufferedReader(new InputStreamReader(fStream)); 


      while (in.ready()) { 
       //System.out.println(in.readLine()); 
       String line = in.readLine(); 
       String keyword = "name="; //keyword to delete in txt file 
       String newLine=line.replaceAll(keyword,""); //delete lines that say name= 
       BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("testEdited.txt")); 
       out.write(newLine.getBytes()); 
       out.close(); 

      } 
      in.close(); 

     } catch (IOException e) { 
      System.out.println("File input error"); 
     } 

    } 
} 

在testEdited文件的输出是这样的:

迈克

显然我想只剩下5名。谁能帮我吗? 感谢

+1

您的'新的FileOutputStream'将始终写入文件开头的数据。考虑使用另外一个将append作为布尔参数的构造函数。或者在顶部打开一次,然后在程序结束时关闭一次。哦,这是功课吗? – 2012-01-31 02:07:56

+0

不,我要创建这个程序来帮助一个不同类的数据挖掘项目,我需要删除不需要的表数据,并试图刷我的Java。 – user1170757 2012-01-31 02:10:39

回答

2

试试这个:

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("testEdited.txt",true)); 

true将数据添加到您的文件。

+1

非常感谢。这就是我需要的。 – user1170757 2012-01-31 02:56:32

0

对于并行读写操作,不能使用BufferedInputStream/BufferedOutputStream。 如果您想要同时读取和写入文件,请使用RandomAccessFile

+0

dest文件与源文件不同。 – Bill 2012-01-31 02:21:09

+0

哎呀..谢谢你指出比尔。 – NiranjanBhat 2012-01-31 03:54:51

2

尝试......

 String line; 
     BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("testEdited.txt")); 

     while ((line = in.readLine()) != null) { 
      String newLine=line.replaceAll("name=",""); 
      out.write(newLine.getBytes()); 
     } 
     out.close(); 
     in.close(); 

没有必要继续打开和关闭输出文件。

另外关于“name =”声明,分配给变量没有多少意义,只能在紧随其后的行上使用它。如果它需要是一个共享的常量,请在某个类的某个类中声明它为(private|public) static final String foo = "bar";

此外,将文件输出流(或文件写入器)封装在适当的缓冲版本中没有太多好处,操作系统会自动为您缓冲写入,并且在此方面做得很好。

您还应该用读取器替换您的流并在finally块中关闭文件。