字符流
单字节读取
只能用来操作文本
Writer (所有输出流的父类)
FileWriter
构造方法(绑定写入的路径):
文件
字符串
mac系统下 一个字 3个字节 UTF-8
windows 一个字 俩字节 GBK 简体中文
FileWriter fw = new FileWriter("文件路径")
fw.write(100)
// 字符输出流 写入文件时
// 需要调用刷新方法
// 建议: 每次写入 都刷新一次
fw.flush()
// 字符数组写入
char[] c = { 'z', 'h', 'a', 'n', 'g' }
fw.write(c)
fw.flush()
fw.write(c, 1, 3)
fw.flush()
// 使用字符串直接写入
fw.write("写一句古诗\n")
fw.flush()
fw.write("床前明月光\n疑是地上霜\n举头望明月\n低头思故乡\n")
fw.flush()
fw.write("白日依山尽", 1, 2)
// 关闭资源前 会刷新
fw.close()
Reader (所有字符输入流的父类)
FileReader
FileReader fr = new FileReader("/Users/C/Desktop/Test/haha.txt");
int num = 0;
char[] c = new char[1024];
while ((num = fr.read(c)) != -1) {
System.out.println(new String(c, 0, num));
}
fr.close();
"利用字符流复制文件(带异常处理)"
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("文件路径");
fos = new FileOutputStream("");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void copyDir(File oFile, File nFile ){
File newFile = new File(nFile, oFile.getName());
newFile.mkdir();
File[] listFiles = oFile.listFiles();
for (File subFile : listFiles) {
if (subFile.isFile()) {
FileWriter fw = null;
FileReader fr = null;
try {
fr = new FileReader(subFile);
File tempFile = new File(nFile, subFile.getName());
fw = new FileWriter(tempFile);
int len = 0;
char[] b = new char[1024];
while ((len = fr.read(b)) != -1) {
fw.write(b, 0, len);
}
} catch (FileNotFoundException e) {
throw new RuntimeException();
} catch (IOException e) {
throw new RuntimeException("关闭资源失败");
} finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
throw new RuntimeException("关闭资源失败");
}
}
}else {
copyDir(subFile, newFile);
}
}
}
转换流
OutputStreamWriter(字符流转向字节流)
作用: 可以根据不同编码格式写入
需要使用到 FileOutputStream 类
InputStreamWriter(字节流转向字符流)
作用: 可以读取不同编码格式的文件
需要使用到 FileInputStream 类
public static void main(String[] args) throws IOException {
getUTF8();
getGBK();
readerGBK();
readerUTF8();
}
public static void readerGBK() throws IOException {
FileInputStream fis = new FileInputStream("文件路径/GBK.txt");
InputStreamReader isr = new InputStreamReader(fis, "GBK");
char[] c = new char[1024];
int len = 0;
while ((len = isr.read(c)) != -1) {
System.out.println(new String(c, 0, len));
}
isr.close();
}
public static void readerUTF8() throws IOException {
FileInputStream fis = new FileInputStream("文件路径/utf8.txt");
InputStreamReader isr = new InputStreamReader(fis);
char[] c = new char[1024];
int len = 0;
while ((len = isr.read(c)) != -1) {
System.out.println(new String(c, 0, len));
}
isr.close();
}
public static void getUTF8() throws IOException {
FileOutputStream fos = new FileOutputStream("文件路径/utf8.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("张三");
osw.close();
}
public static void getGBK() throws IOException {
FileOutputStream fos = new FileOutputStream("文件路径/GBK.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
osw.write("张三");
osw.close();
}