Java字符串写入文件三种方式的实现

 更新时间:2017年06月09日 15:48:52   作者:孙_悟_空  
这篇文章主要介绍了 Java字符串写入文件三种方式的实现的相关资料,需要的朋友可以参考下

 Java字符串写入文件三种方式的实现

1、使用FileWriter

String str="hello world!";
    FileWriter writer;
    try {
      writer = new FileWriter("E:/token.txt");
      writer.write(str);
      writer.flush();
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

2、使用FileOutPutStream

File txt=new File("E:/log1.txt");
       if(!txt.exists()){ 
         txt.createNewFile(); 
      } 
       byte bytes[]=new byte[512];  
       bytes=str.getBytes(); 
       int b=bytes.length;  //是字节的长度,不是字符串的长度
       FileOutputStream fos=new FileOutputStream(txt); 
       fos.write(bytes,0,b); 
       fos.write(bytes);
       fos.close();

3、使用FileOutPutStream追加写入文件

FileOutputStream fos = new FileOutputStream("E:/log.txt",true);
//true表示在文件末尾追加 
fos.write(log.getBytes()); 
fos.close();

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

最新评论