您的位置:首页 > 编程语言 > Java开发

Java - IO - 字符流 - Writer - Reader

2014-09-05 21:17 399 查看
public class IoTest {
/***************
* 把文件1的内容复制到另一个文件2中 读取文件1的内容 写入到文件2中
*
* 一个字符一个字符的读和写
***/
public static void main(String[] args) {
// 1.创建一个读取字符文件的读取流对象 FileReader
FileReader fr = null;
// 2.创建一个写入字符文件的写入流对象 FileWriter
FileWriter fw = null;
//监视异常
try {
//读取abc.txt文件
fr = new FileReader("abc.txt");
//写入到abc.txt文件
fw = new FileWriter("abc2.txt");
//创建缓冲区,创建一个char字符来存放读取到 的字符,如果已到达流的末尾,则返回 -1
int ch = 0;
//循环读写操作
while((ch = fr.read())!=-1){
fw.write(ch);
}
} catch (IOException e) {
throw new RuntimeException("读写失败");
} finally {//关闭两个文件流对象
if (fr != null)
try {
fr.close();
} catch (IOException e) {
throw new RuntimeException("读取流对象关闭失败");
}
if (fw != null)
try {
fw.close();
} catch (IOException e) {
throw new RuntimeException("写入流对象关闭失败");
}
}
System.out.println("复制成功");
}

}

package myio;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class IoTest2 {
/***************
* 把文件1的内容复制到另一个文件2中 读取文件1的内容 写入到文件2中
*
* 一个数组一个数组的读和写
***/
/*****
* int read() 返回读取到的字符,如果已到达流的末尾,则返回 -1
* int read(char[] cbuf, int offset, int length)  返回:读取的字符数,如果已到达流的末尾,则返回 -1
* int read(char[] cbuf)  返回:读取的字符数,如果已到达流的末尾,则返回 -1
* write(char[] cbuf, int off, int len) 存入一个字符数组
* write(int c) 存入一个字符
* write(String str, int off, int len)
* close()
***/
public static void main(String[] args) {
// 1.创建一个读取字符文件的读取流对象 FileReader
FileReader fr = null;
// 2.创建一个写入字符文件的写入流对象 FileWriter
FileWriter fw = null;
//监视异常
try {
//读取abc.txt文件
fr = new FileReader("abc.txt");
//写入到abc.txt文件
fw = new FileWriter("abc4.txt");
//创建缓冲区char字符数组来存放读取到的字符。
char[] buffer = new char[1024];
//读取的字符数,如果已到达流的末尾,则返回 -1
int len;
//循环读写操作
while((len = fr.read(buffer))!=-1){
fw.write(buffer,0,len);
}
} catch (IOException e) {
throw new RuntimeException("读写失败");
} finally {//关闭两个文件流对象
if (fr != null)
try {
fr.close();
} catch (IOException e) {
throw new RuntimeException("读取流对象关闭失败");
}
if (fw != null)
try {
fw.close();
} catch (IOException e) {
throw new RuntimeException("写入流对象关闭失败");
}
}
System.out.println("复制成功");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐