java基础—IO流——复制一个文件到当前文件夹中

来源:互联网 发布:linux cp实现 编辑:程序博客网 时间:2024/04/29 12:21


复制一个文件到当前文件夹中


import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;//复制一个文件到当前的文件夹中public class FileReaderAndWriter {public static void main(String[] args) {System.out.println("<><><><>______复制文件功能到当前的文件夹中______<><><><>");// 关联一个需要复制的文件FileReader  fr = null ; //创建一个写入文件的对象FileWriter  fw = null;try {//初使化对象fr = new FileReader("C:\\Users\\Administrator\\Desktop\\测试文件夹\\新建文本文档.txt");fw = new FileWriter("C:\\Users\\Administrator\\Desktop\\测试文件夹\\新建文本复件.txt");//调用数组的方法来读取文件数据并写入文件char[] c = new char[1024];int len = 0;while((len=fr.read(c))!=-1){fw.write(c,0,len);fw.flush();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {fr.close();} catch (IOException e) {e.printStackTrace();}try {fw.close();} catch (IOException e) {e.printStackTrace();}}}}

运行程序:




复制一个文件到当前文件夹下,加入缓冲技术



import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;//复制一个文件到当前的文件夹中public class FileReaderAndWriter {public static void main(String[] args) {method2();}private static void method2() {// TODO Auto-generated method stubSystem.out.println("<><><><>______复制文件功能到当前的文件夹中______加入了缓冲技术<><><><>");//创建一个缓冲区对象BufferedReader br = null;BufferedWriter bw = null;// 关联一个需要复制的文件FileReader  fr = null ; //创建一个写入文件的对象FileWriter  fw = null;try {//初使化对象fr = new FileReader("C:\\Users\\Administrator\\Desktop\\测试文件夹\\新建文本文档.txt");fw = new FileWriter("C:\\Users\\Administrator\\Desktop\\测试文件夹\\新建文本复件.txt");br = new BufferedReader(fr);bw = new BufferedWriter(fw);//调用数组的方法来读取文件数据并写入文件//char[] c = new char[1024];//int len = 0;//调用缓冲区中每次可以读取一行的功能String len = null;while((len=br.readLine())!=null){bw.write(len);System.out.println(len);//启用换行的功能bw.newLine();//刷新bw.flush();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {br.close();} catch (IOException e) {e.printStackTrace();}try {bw.close();} catch (IOException e) {e.printStackTrace();}}}}

运行程序:











0 0
原创粉丝点击