Java IO(字符流)复制文件

1.复制文件(包含中文)

​
/**
 * 
 * @param path 目标文件
 * @param target 需要复制到的指定文件
 * @return boolean true 复制成功 ;false 复制失败
 * @throws IOException
 */
 
public static boolean copy(String path, String target) throws IOException {
	 long start = System.currentTimeMillis();
	File file=new File(path);
	if(!file.exists()){
		System.out.println("源文件不存在!");
		return false;
	}
	File targetfile=new File(path);
	if(!targetfile.getParentFile().exists()){//创建父目录
		targetfile.getParentFile().mkdirs();
	}
	FileReader fr=new FileReader(file);
	FileWriter fw=new FileWriter(target);
     char [] buf=new char[1024];
      int len;
	while((len=fr.read(buf))!=-1){
		fw.write(new String(buf, 0, len));
		System.out.println(new String(buf, 0, len));
	}
	fr.close();
	fw.close();
	long end=System.currentTimeMillis();
	System.out.println("总共耗时:"+(end-start)+"毫秒");
	return true;
}

​

2.复制二进制文件(图片)

/**
 * 
 * @param path 目标文件
 * @param target 需要复制到的指定文件
 * @return boolean true 复制成功 ;false 复制失败
 * @throws IOException
 */
 
private static boolean copy(String path, String target) throws IOException {
	 long start = System.currentTimeMillis();
	File file=new File(path);
	if(!file.exists()){
		System.out.println("源文件不存在!");
		return false;
	}
	File targetfile=new File(target);
	if(!targetfile.getParentFile().exists()){//创建父目录
		targetfile.getParentFile().mkdirs();
	}
	InputStream is=new FileInputStream(file);
	OutputStream os=new FileOutputStream(targetfile);
     byte [] buf=new byte[1024];
     int len;
	while((len=is.read(buf))!=-1){
		os.write(buf, 0, len);
		System.out.println(new String(buf, 0, len));
	}
	is.close();
	os.close();
	long end=System.currentTimeMillis();
	System.out.println("总共耗时:"+(end-start)+"毫秒");
	return true;
}

猜你喜欢

转载自blog.csdn.net/qq_29393273/article/details/84873756