• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

java写入文件的几种方法

java 搞代码 4年前 (2022-01-09) 12次浏览 已收录 0个评论

一,FileWritter写入文件

FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,然而,当指定一个true (布尔)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾。

1. 替换所有现有的内容与新的内容。

new FileWriter(file);2. 保留现有的内容和附加在该文件的末尾的新内容。

代码如下:new FileWriter(file,true);

追加文件示例
一个文本文件,命名为“javaio-appendfile.txt”,并包含以下内来2源gaodaima#com搞(代@码&网容。

ABC Hello追加新内容 new FileWriter(file,true)

代码如下:package com.yiibai.file;import java.io.File;import java.io.FileWriter;import java.io.BufferedWriter;import java.io.IOException;public class AppendToFileExample {    public static void main( String[] args )    {      try{      String data = " This content will append to the end of the file";      File file =new File("javaio-appendfile.txt");      //if file doesnt exists, then create it      if(!file.exists()){       file.createNewFile();      }      //true = append file      FileWriter fileWritter = new FileWriter(file.getName(),true);             BufferedWriter bufferWritter = new BufferedWriter(fileWritter);             bufferWritter.write(data);             bufferWritter.close();         System.out.println("Done");     }catch(IOException e){      e.printStackTrace();     }    }}

结果
现在,文本文件“javaio-appendfile.txt”内容更新如下:

ABC Hello This content will append to the end of the file

二,BufferedWriter写入文件

缓冲字符(BufferedWriter )是一个字符流类来处理字符数据。不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符数据保存到文件。

代码如下:package com.yiibai.iofile;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;public class WriteToFileExample { public static void main(String[] args) {  try {   String content = "This is the content to write into file";   File file = new File("/users/mkyong/filename.txt");   // if file doesnt exists, then create it   if (!file.exists()) {    file.createNewFile();   }   FileWriter fw = new FileWriter(file.getAbsoluteFile());   BufferedWriter bw = new BufferedWriter(fw);   bw.write(content);   bw.close();   System.out.println("Done");  } catch (IOException e) {   e.printStackTrace();  } }}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:java写入文件的几种方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址