FileWritter写入文件
来源:互联网 发布:开店记账软件 编辑:程序博客网 时间:2024/06/01 09:59
java写入文件的几种方法小结
一,FileWritter写入文件
FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,然而,当指定一个true (布尔)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾。
1. 替换所有现有的内容与新的内容。
new FileWriter(file);2. 保留现有的内容和附加在该文件的末尾的新内容。
代码如下
new FileWriter(file,true);
追加文件示例
一个文本文件,命名为"javaio-appendfile.txt",并包含以下内容。
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();
}
}
}
- FileWritter写入文件
- FileWritter写入文件
- FileWritter写入文件
- java FileWritter,BufferedWriter 写入文件
- java FileWritter,BufferedWriter 写入文件
- 文件写入
- 文件写入
- 写入文件
- 写入文件
- 写入文件
- 写入文件
- 写入文件
- 写入文件
- 文件写入
- 文件写入
- [C#] 文本写入文件,追加写入文件
- 写入日志文件
- Excel文件写入
- c语言实现抽象数据类型(信息隐藏)
- java接口的细节!
- VC 6.0 编译支持中文的LUA5.23静态库
- c操作lua栈 6
- String对象及特点
- FileWritter写入文件
- 类的序列化与网络通讯
- ISE 14.4初级入门——01
- 八个被现代科学证实的古老信条
- 强制类型转换
- 将printStackTrace()的信息以字符串形式保存
- Google Geocoding API 免费版和商业版(地理编码逆地址)
- 设计模式读书笔记-----解释器模式
- perl cpanm