您的位置:首页 > 其它

IO流--拷贝文本文件

2015-12-02 07:50 260 查看
//将文本文件复制到当前目录。

/*
流式:
复制原理:
其实就是将文件数据存储到当前目录的一个文件中。

步骤:
1.在当前目录创建一个同名文件,用于存储文件中的数据。
2.定义读取流和原文件关联。
3.通过不断的读写完成数据存储。
4.关闭资源。
*/
import java.io.*;
class CopyText {
public static void main(String[] args) {
copy_1();
copy_2();
}

//读一个字符,就写一个字符。
public static void copy_1(){
FileWriter fw = null;
FileReader fr = null;
try{
//创建目的地
fw = new FileWriter("RuntimeDemo_copy.java");

//与已有文件关联
fr = new FileReader("RuntimeDemo.java");

int ch = 0;
while((ch = fr.read()) != -1){
fw.write(ch);
}
}
catch (IOException e){
throw new RuntimeException("读写失败!");
}finally{
try{
if(fr != null)
fr.close();
}catch (IOException e){
System.out.println(e.toString());
}
try{
if(fw != null)
fw.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}

//读完一块写。
public static void copy_2(){
FileWriter fw = null;
FileReader fr = null;
try{
//创建目的地
fw = new FileWriter("RuntimeDemo_copy.java");

//与已有文件关联
fr = new FileReader("RuntimeDemo.java");

char[] buffer = new char[1024];

int length = 0;
while((length = read(buffer)) != -1){
fw.write(buffer,0,length);
}
}catch (IOException e){
throw new RuntimeException("读写失败!");
}finally{
try{
if(fr != null)
fr.close();
}catch (IOException e){
System.out.println(e.toString());
}
try{
if(fw != null)
fw.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}
/*-----------------------------------------------------------------*/
/*
通过缓冲区复制一个.java文件。
readLine()方法返回的时候只返回回车符之前的数据内容,并不返回回车符。
*/
import java.io.*;
class CopyText {
public static void main(String[] args) {
copy_1();
}

//读一个字符,就写一个字符。
public static void copy_1(){
BufferedReader br = null;
BufferedWriter bw = null;
try{
//创建缓冲区
br = new BufferedReader(new FileReader("RuntimeDemo.java"));

bw = new BufferedWriter(new FileWriter("RuntimeDemo.java"));

String line = null;
while((line = br.readLine()) != null){
bw.write(line);
bw.newLine();
bw.flush();
}
}catch (IOException e){
throw new RuntimeException("读写失败!");
}finally
{
try{
if(br != null)
br.close();
}catch (IOException e){
System.out.println(e.toString());
}try{
if(bw != null)
bw.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: