栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java文件复制代码片断(java实现文件拷贝)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java文件复制代码片断(java实现文件拷贝)

一、要完成这个程序需要了解的知识点:

1、编写简单的Java程序,比如hello world ---废话了。。。。哈哈
2、了解java的文件操作
3、了解java的buffer操作
4、对文件操作的一些异常处理点:1、源文件不能读取到的情况。 2、目的文件创建失败的情况 3、文件锁问题 4、字符乱码问题。。。可能不全啊

这些是需要用到的包

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; IO操作时需要做异常处理

个人感觉这个效率高的方式,安装计算机来讲,效率高的操作应该是对内存的操作是比较高的了,直接对IO的操作应该是相对低的。。所以这里选的是就是读到内存在统一写IO,代码如下:

package com.itheima;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;



public class Test5 {

	public static void main(String[] args) throws IOException {
		String src_file = "D:/java/java.doc";
		String des_file = "D:/java/java_copy.doc";
		
		copyFile(src_file, des_file);
		
		System.out.println("OK!");
	}

	public static void copyFile(String src, String des) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(src));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(des));

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}

	}
}

其它网友的补充

try {
      File inputFile = new File(args[0]);
      if (!inputFile.exists()) {
 System.out.println("源文件不存在,程序终止");
 System.exit(1);
      }
      File outputFile = new File(args[1]);
      InputStream in = new FileInputStream(inputFile);
      OutputStream out = new FileOutputStream(outputFile);
      byte date[] = new byte[1024];
      int temp = 0;
      while ((temp = in.read(date)) != -1) {
 out.write(date);
      }
      in.close();
      out.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152699.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号