分享

使用java实现在文件中添加字符串...

 nbtymm 2007-01-18

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class FileWriterTest {

 public static void main(String[] args) {
  FileOutputStream stream ;
  OutputStreamWriter writer;
  try {

//主要是使用了FileOutputStream的构造函数FileOutputStream(File file, boolean append) 
//这里参数append为true表示可以添加,详细使用参考JDK帮助文档资料.
  stream = new FileOutputStream("C:\\WINDOWS\\system32\\drivers\\etc\\hosts", true);
writer =  new OutputStreamWriter(stream);
  writer.write("202.206.219.246    rsgl_dbserve");
  writer.close();
  stream.close();
  } catch (IOException e) {
   
   e.printStackTrace();
  }
  
 }

}

以上代码在eclipse上调试成功!

 

为了增加代码的重用性,可以编写一个方法如下:

 

public void appendToFile(String str, String filename) throws Exception
   {
      // Open up an outputstreamwriter to the file, and append str to it.
      FileOutputStream stream;//provides file access
      OutputStreamWriter writer;//writes to the file
      try
      {
         stream = new FileOutputStream(filename, true);
         writer = new OutputStreamWriter(stream);
         writer.write(str);
         writer.close();
         stream.close();
      }
      catch(Exception e)
      {
         throw e;
      }
   }//appendToFile

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多