1.java.io.Writer和java.io.OutputStream的区别
OutputStream | Writer |
---|---|
字节流,以byte为单位 | 字符流,以char为单位 |
写入字节(0-255):void write(int b) | 写入字符(0-65535):void write(int c) |
写入字节数组 void write(byte[] b) | 写入字符数组void wirlte(char[] c) |
void write(byte[] b, int off, int len) | void write(char[] c, int off, int len) |
可以直接写入字符串wirte(String s) |
2.Writer
java.io.Writer是所有字符输出流的超类:
- void write(int c):写入一个字符(0-65535)
* write方法也是阻塞的。必须等待write方法返回才能执行下一行代码
* FileWriter可以从文件获取Writer,字符编码是系统默认的UTF-8。修改编码格式参见2.3
Writer writer = new FileWriter("test.txt");
- void write(char[] c):写入字符数组的所有字符
- void write(char[] c, int off, int len):写入字符数组指定范围的字符
- void write(String s):写入String表示的所有字符
- void close():关闭Writer流
2.1Writer写入单个字符:
static void writeFile1(String file) throws IOException{
//手动关闭
Writer writer = new FileWriter(file);
writer.write(65);
writer.close();
}
static void writeFile2(String file) throws IOException{
//try..finall关闭Writer流
Writer writer = null;
try{
writer = new FileWriter(file);
writer.write(66);
}finally {
writer.close();
}
}
static void writeFile3(String file) throws IOException{
//使用try(resource)自动关闭Writer流
try(Writer writer = new FileWriter(file)){
writer.write(67);
}
}
2.2Writer一次写入多个字符或字符串
static void writeFile4(String file) throws IOException{
try(Writer writer = new FileWriter(file)){
writer.write("Hello ".toCharArray());//写入char数组
writer.write("world");//写入字符串
}
}
2.3Writer实际上是基于OutputStream构造的:
- FileWriter内部持有一个FileOutputStream
- Writer可以通过OutputStream构造
OutputStream output = new FileOutputStream(filename);
Writer writer = new OutputStreamWriter(output, "UTF-8");//使用OutputStream写入byte
public static void main(String[] args) throws IOException,ClassNotFoundException {
String file = "./src/main/java/com/testList/output.txt";
try(Writer writer = new OutputStreamWriter(
new FileOutputStream(file),"utf-8")) {
writer.write("Hello ");
writer.write("你好");
}
}
2.4CharArrayWriter可以在内存中模拟一个Writer
public static void main(String[] args) throws IOException,ClassNotFoundException {
try(CharArrayWriter writer = new CharArrayWriter()){
writer.write(65);
writer.write(66);
writer.write(67);
char[] data = writer.toCharArray();
System.out.println(data);
}
}
## 3.总结
* Writer定义了所有字符输出流的超类
* FileWriter实现了文件字符流输出
* CharArrayWriter在内存中模拟一个字符流输出
* Writer是基于OutputStream构造的:
* FileWriter使用系统默认编码,无法指定编码
* 可以通过OutputStreamWriter指定编码
* 使用try(resource)保证Writer正确关闭