Java 实现复制文本文件的两种方法

来源:互联网 发布:js数组concat 编辑:程序博客网 时间:2024/05/17 07:08

Java实现复制文本文件的两种方法

FileChannel这个类是继承于抽象类AbstractInterruptibleChannel,实现了接口ByteChannel,GatheringByteChannel,ScatteringByteChannel。

FileChannel这个是最便捷的方法实现复制文件,当然也有一种笨的方法实现复制文件,用读取文件,创建文件,写入文件的方法实现FileChannel这个方法

FileChannel 方法实现复制文本

public class MainCopy {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubFileChannel in=null;FileChannel out=null;File f1=new File("channel1.txt");File f2=new File("channel2.txt");try {in=new FileInputStream(f1).getChannel();ByteBuffer byteBu=in.map(FileChannel.MapMode.READ_ONLY, 0,f1.length());out=new FileOutputStream(f2).getChannel();out.write(byteBu);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {in.close();out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

用读写文件的方法实现

<pre name="code" class="java">public class MainCopy2 {static PrintWriter pw=null;/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException {// TODO Auto-generated method stub//读取文件InputStream in=new FileInputStream("channel1.txt");InputStreamReader iread=new InputStreamReader(in);BufferedReader bf=new BufferedReader(iread);//复制文件File f2=new File("channel2.txt");OutputStream os=new FileOutputStream(f2);OutputStreamWriter ow=new OutputStreamWriter(os);    pw=new PrintWriter(ow);String len=null;while((len=bf.readLine())!=null){copyfile(len);}bf.close();pw.close();}//复制两个文件的内容static void copyfile(String content) throws FileNotFoundException{pw.println(content);}}




1 0
原创粉丝点击