import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class WriterDemo {
/*
* Writer:字符输出流。
* FileWriter:文件字符输出流。以字符为传输单位进行数据传输
* ---->构造方法
* 1.new FileWriter(File file)
* 参数file对象为目标文件对象。
* 2.new FileWriter(File file,boolean append):
* File对象为目标文件,boolean append代表是否续写。
* true为续写,false为覆盖。
* 3.new FileWriter(String pathName)
* 传入目标文件的路径。如果该文件的父级路径存在,则直接
* 创建文件,如果父级路径不存在会抛异常。
* 4.new FileWriter(String pathName,boolean append)
* 传入目标文件的路径。如果该文件的父级路径存在,则直接
* 创建文件,如果父级路径不存在会抛异常。
* boolean append代表是否续写。
* true为续写,false为覆盖。
*/
public static void main(String[] args) {
File file = new File("D:/demo/test/b.txt");
File parent = file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Writer wr = null;
try {
wr = new FileWriter(file);
/*
* write(int c):
* 一次写入一个字符
*/
// wr.write('中');
// wr.flush();//刷新
/*
* write(char[] cbuf):
* 把char数组中的内容写入文件中
*/
/*char[] c = {'今','天','高','考','了'};
wr.write(c);
*/
/*
* write(char[] cbuf,int off,int len):
* 把char数组从下标off开始len个字符写入文件
*/
/*char[] c = {'今','天','高','考','了'};
wr.write(c, 2, 2);
*/
/*
* write(String str):
* 直接将参数字符串写入文件
*/
/* wr.write("今天天气好晴朗!");
*/
/*
* write(String str,int off,int len):
* 把字符串str从下标off开始len个字符写入文件
*/
String str = "今天天气好晴朗";
wr.write(str, 2, 5);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(wr!=null){
try {
/*
* close()在所有的流中都是关闭的含义
* 只有在字符输出流的时候是先刷新,后关闭。
*/
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Writer 简介
最新推荐文章于 2021-07-01 21:00:42 发布
948

被折叠的 条评论
为什么被折叠?



