操作的File的一个小工具

// 保存下,都是对文件上传时遇到的一些问题,保存了以后用的时候直接来看
package com.zte.xh.fund.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

import javax.servlet.http.HttpServletResponse;

/**
 * 用来对文件操作的一些方法
 * 
 * @author Jay_Lee
 *
 */
public class FileUtil {
	// copy图片文件
	public static void copyFile(File sourceFile, File toFile) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(sourceFile);
			fo = new FileOutputStream(toFile);
			// 得到对应的文件通道
			in = fi.getChannel();
			// 得到对应的文件通道
			out = fo.getChannel();
			// 连接两个通道,并且从in通道读取,然后写入out通道
			in.transferTo(0, in.size(), out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {

				e.printStackTrace();

			}
		}
	}

	// 获取新的文件名
	public static String newFileName(String name) {
		String type = name.substring(name.indexOf("."), name.length());
		String newn = String.valueOf(System.currentTimeMillis());
		return newn + type;
	}

	// 输出图片到页面预览或预览
	public static void outFile(String filePath, HttpServletResponse resp)
			throws Exception {

		File file = new File(filePath);
		FileInputStream fis = new FileInputStream(file);

		OutputStream out = resp.getOutputStream();
		byte[] tempB = new byte[1024];
		int tempFlag;
		while ((tempFlag = fis.read(tempB)) != -1) {
			out.write(tempB, 0, tempFlag);
		}
		fis.close();
		out.close();
	}

	// 测试demo
	public static void main(String[] args) {
		copyFile(
				new File(
						"D:\\test\\test\\1.png"),
				new File(
						"D:\\test\\1.png"));
		//
		System.out.println(newFileName("test.png"));
	}
}

猜你喜欢

转载自lijie-insist.iteye.com/blog/2228187