标题
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
/*
* FileReader/FileWriter类
* 文件字符输入输出流
*/
public class Test03 {
public static void main(String[] args) throws IOException {
test3();
}
// 文件字符输入流
public static void test1() throws IOException {
Reader reader = new FileReader("D:\\Java\\hello.txt");
// 每次读取一个字符
int data = reader.read();// 返回一个int类型的字符值
while (data != -1) {
System.out.println((char) data);
data = reader.read();
}
reader.close();
}
// 文件字符输出流
public static void test2() throws IOException {
Writer writer = new FileWriter("D:\\Java\\hello.txt", true);
writer.write("余书磊");
writer.flush();
System.out.println("使用字符输出流写入成功!");
writer.close();
}
// 文件复制
public static void test3() throws IOException {
Reader reader = new FileReader("D:\\Java\\hello.txt");
Writer writer = new FileWriter("D:\\Java\\hello_bak.txt");
//方式一:每次复制一个字符
int data = reader.read();
while (data != -1) {
writer.write(data);
data = reader.read();
}
//方式二:每次复制一个字符数组
char[] buffer=new char[10];
int num=reader.read(buffer);//返回实际读取的长度
while(num!=-1){
writer.write(buffer, 0, num);
num=reader.read(buffer);
}
//方式三:将读取的字符拼接到字符串中,再写入
StringBuffer sb=new StringBuffer();
int data = reader.read();
while (data != -1) {
sb.append((char)data);
data = reader.read();
}
writer.write(sb.toString());
writer.flush();
System.out.println("文件复制成功!");
writer.close();
reader.close();
}
/*
* 字符流无法复制二进制文件,字节流可以
*/
public static void test4() throws IOException {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\Java\\ascii.jpg"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\Java\\ascii_bak.jpg"));
int data = bis.read();
while (data != -1) {
bos.write(data);
data = bis.read();
}
bos.flush();
System.out.println("文件复制成功!");
bos.close();
bis.close();
}
}
时间: 2024-10-05 09:28:38