操作的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"));
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值