服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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

    我在一个项目中需要使用c:/windows/system32/drivers/etc这个目录下的hosts文件,并且在该文件的最后加上一个这样的字符串:"202.206.219.246    rsgl_dbserve",由于对java的文件操作不是很熟练,花了半天的功夫才找到了,具体的实现办法如下:

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

扫描关注微信公众号