package demo.io;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class 字符流 {
private static final int BUFFER_SIZE = 1024;//缓冲区长度
public static void main(String[] args) {
// fileWriterDemo();//字符流写操作
// fileReaderDemo();//字符流读操作
test();//测试:复制文本内容
}
//测试:复制文本内容
private static void test() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("后期设备的配置文件.properties");
fw = new FileWriter("I:\\后期设备的配置文件.properties");
char[] buf = new char[BUFFER_SIZE * 4];//读取到的字符串
int len = 0;//读取字符串长度
while ((len = fr.read(buf)) != -1) {
fw.write(buf, 0, len);//char[] 写入
// fw.write(new String(buf, 0 , len));//String 写入
}
/*while ((len = fr.read()) != -1) {
fw.write(len);//int 写入
}*/
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null)
fr.close();
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//字符流读操作
private static void fileReaderDemo() {
FileReader fr = null;
try {
fr = new FileReader("aaa.txt");
int len = 0;
/*
while ((len = fr.read()) != -1 ) {//逐一读取字符
System.out.print((char) len);
}*/
// char[] buf = new char[3];
char[] buf = new char[1024];//常用
while ((len = fr.read(buf)) != -1) {//读取多少长度的字符,构造相应长度的字符串
System.out.print(new String(buf, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//字符流写操作
private static void fileWriterDemo() {
//FileWriter fw = new FileWriter("后期设备的配置文件.properties");//创建文件并覆盖
FileWriter fw = null;//创建文件,打开追加模式
try {
fw = new FileWriter("k:\\aaa.txt", true);
fw.write("ab" + 123 + "xczv\n");
fw.write("xxxxxxxxxxxxxxxxxxxxx\n");
fw.flush();//刷新该流的缓冲 若不刷新,缓冲区的数据只能在关闭流时写入
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();//关闭字符流
} catch (IOException e) {
throw new RuntimeException("关闭失败");
}
}
}
}
}
/**
* 输入流和输出流相对于内存设备而言.
* <p>
* 将外设中的数据读取到内存中:输入
* 将内存的数写入到外设中:输出。
* <p>
* <p>
* 字符流的由来:
* 其实就是:字节流读取文字字节数据后,不直接操作而是先查指定的编码表。获取对应的文字。
* 在对这个文字进行操作。简单说:字节流+编码表
*/