文件工具类,一些常用的文件方法

本文介绍了一个实用的Java工具类,用于处理文件的客户端输出、下载和媒体播放等功能。包括了如何将不同类型的文件输出到客户端浏览器,实现文件的预览、下载及媒体文件的在线播放。同时提供了获取文件存储路径和临时目录的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class FileUtil {

	/**
	 * 将文件输出到客户端,一般用于预览
	 * @param file
	 * @param contentType   图片    image/jpeg
	 * 						视频   audio/mpeg
	 * 						应用程序   application/octet-stream
	 */
	public static void renderFileToClient(File file, String contentType) {
		OutputStream toClient = null;
		InputStream fis = null;
		byte[] buffer = null;
		HttpServletResponse response = SpringMVCUtil.getResponse();
		try {
			fis = new BufferedInputStream(new FileInputStream(file));
			buffer = new byte[1024];
			response.reset();
			response.setContentLength(Long.valueOf(file.length()).intValue());
			response.setContentType(contentType);
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			toClient = new BufferedOutputStream(response.getOutputStream());
			int bytesRead;
			while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
				toClient.write(buffer, 0, bytesRead);
				toClient.flush();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (toClient != null) {
				try {
					toClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 获取附件存储相对路径
	 * 
	 * @param attachmentConfig
	 * @return
	 */
	public static String getRelativePath() {
		StringBuilder sBuilder=new StringBuilder();
		// 模块名未定
		String dateStr = DateUtil.getCurrDateString().replaceAll("-", "");
		sBuilder.append(dateStr.substring(0, 4) + "/");
		sBuilder.append(dateStr.substring(4, 6) + "/");
		sBuilder.append(dateStr.substring(6, 8) + "/");

		return sBuilder.toString();
	}
	
	/**
	 * 获取临时目录
	 * 
	 * @return
	 */
	public static String getTempDir() {
		String tempPath = System.getProperty("java.io.tmpdir");
		File tempFile = new File(tempPath);
		if (!tempFile.exists()) {
			tempFile.mkdirs();
		}
		return tempFile.getAbsolutePath() + "/";
	}
	
	/**
	 * 下载文件
	 * 
	 * @date 2015-8-25 下午9:13:13
	 * @param srcPath
	 */
	public static void download(String downLoadPath) {
		HttpServletResponse response = SpringMVCUtil.getResponse();
		response.setContentType("text/html;charset=utf-8");   
        response.setCharacterEncoding("UTF-8");   
        BufferedInputStream bis = null;   
        BufferedOutputStream bos = null;
        File file = new File(downLoadPath);
        try {   
            response.setContentType("application/x-msdownload;");   
            response.setHeader("Content-disposition", "attachment; filename="+ new String(file.getName().getBytes("utf-8"), "ISO8859-1"));   
            response.setHeader("Content-Length", String.valueOf(file.length()));   
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));   
            bos = new BufferedOutputStream(response.getOutputStream());   
            byte[] buff = new byte[2048];   
            int bytesRead;   
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {   
                bos.write(buff, 0, bytesRead);   
            }   
        } catch (Exception e) {   
            e.printStackTrace();   
        } finally {   
            if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}   
            if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}   
        }   
	}
	
	/**
	 * 向客户端输出浏览内容
	 *
	 * @date 2015-8-31 下午8:10:48
	 * @param file  视频文件
	 * @param contentType  "audio/mpeg"
	 */
	public static void renderMediaToClient(File file, String contentType) {
		OutputStream toClient = null;
		InputStream fis = null;
		byte[] buffer = null;
		HttpServletResponse response = SpringMVCUtil.getResponse();
		try {
			fis = new BufferedInputStream(new FileInputStream(file));
			buffer = new byte[1024];
			response.reset();
			response.setContentLength(Long.valueOf(file.length()).intValue());
			response.setContentType(contentType);
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			toClient = new BufferedOutputStream(response.getOutputStream());
			int bytesRead;
			while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
				toClient.write(buffer, 0, bytesRead);
				toClient.flush();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (toClient != null) {
				try {
					toClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值