import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
/**
* Io流:
* java中 一个 数字或者字母 占用 1个byte =1个字节 ;一个中文 占用 两个字节 = 2byte !!
* 节点流 : 除了以下四个 为节点流 其余的流 均为 处理流
* 1、字节流 InputStream OutputStream 抽象类
* 2、字符流 Reader Writer 抽象类
*
*
* 字节流InputStream /OutputStream 用来处理 非文本文件 : 视频 、音频、图片 等 以字节形式存储的文件。
* 字符流Reader /Writer 用来处理 纯文本文件 :txt 。
*
* 字符流的联系 读取 写出 和复制 联系
*
* char[] c = new char[] 数组来每次读取指定个数的 字符。
*
* @author Administrator
*
*/
public class TestFileReaderFileWriter {
/**
* 文本文件的复制 。
*/
@Test
public void testReaderWriterCopy(){
// 当前java工程下 的文件 : 源文件<需要读取的文件 >必须存在
// File srcfile = new File("1234.doc");
// File destfile = new File("1234copy.doc");
// 当前java工程下 的文件 : 源文件<需要读取的文件 >必须存在
File srcfile = new File("1234.txt");
// 目标文件可以不存在 ,在执行过程中创建 如果 目标文件存在, 则进行覆盖。
File destfile = new File("1234copy.txt");
// 字符流 :输入流
FileReader fr =null;
// 字符流 :输出流
FileWriter fw =null;
try {
fr = new FileReader(srcfile);
fw = new FileWriter(destfile);
// 字符流的 数组单位 用 char[]
char[] c = new char[100];
int len;
while((len = fr.read(c))!=-1){
// 读取的文件内容进行输出。
// String s = new String(c, 0, len);
// System.out.print(s);
// 写入到新文件中
fw.write(c, 0, len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Test
public void testReaderWriter(){
// 当前java工程下 的文件 : 源文件<需要读取的文件 >必须存在
// File srcfile = new File("1234.doc");
// File destfile = new File("1234copy.doc");
// 当前java工程下 的文件 : 源文件<需要读取的文件 >必须存在
File srcfile = new File("1234.txt");
// 目标文件可以不存在 ,在执行过程中创建 如果 目标文件存在, 则进行覆盖。
File destfile = new File("1234copy.txt");
// 字符流 :输入流
FileReader fr =null;
// 字符流 :输出流
FileWriter fw =null;
try {
fr = new FileReader(srcfile);
fw = new FileWriter(destfile);
// 字符流的 数组单位 用 char[]
char[] c = new char[100];
int len;
while((len = fr.read(c))!=-1){
// 读取的文件内容进行输出。
String s = new String(c, 0, len);
System.out.print(s);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
java Io reader writer 笔记3
最新推荐文章于 2024-08-12 22:20:16 发布