IO流——字符流
字符流:只能处理纯文本,全部为可见字符 .txt .html
节点流:Reader FileReader
Writer FileWriter
1.纯文本的读取
import java.io.*;
/**
* 字符流纯文本读取
*/
public class Demo01 {
public static void main(String[] args) {
//1.创建源
File file = new File("D:/IOtest/demo.txt");
//2.选择流
Reader reader = null;
try {
reader = new FileReader(file);
//读取操作
char[] flush = new char[1024];
int len = 0;
while (-1 != (len=reader.read(flush))) {
//字符数组转成字符串
String str = new String(flush,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("源文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2.纯文本的写出
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* 写出文件
*/
public class Demo02 {
public static void main(String[] args) {
//1.创建源
File file = new File("D:/IOtest/char.txt");
//2.选择流
Writer writer = null;
try {
//FileWriter(file,true)中true表示文件写出时为追加,默认为false,表示文件写出时为覆盖
writer = new FileWriter(file);
//3.写出
String msg = "We are family!";
writer.write(msg);
writer.append("I love you!");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.纯文本的拷贝
import java.io.*;
/**
* <span style="font-size:12px;">纯文本的拷贝</span>
*/
public class CopyFileDemo {
public static void main(String[] args) {
//1.创建源
File src = new File("D:/IOtest/demo.txt");
File dest = new File("D:/IOtest/char.txt");
//2.选择流
Reader reader = null;
Writer writer = null;
try {
reader = new FileReader(src);
writer = new FileWriter(dest);
//读取操作
char[] flush = new char[1024];
int len = 0;
while (-1 != (len=reader.read(flush))) {
writer.write(flush,0,len);
}
writer.flush();//强制刷出
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("源文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}