package cn.twinkling.stream.util;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import cn.twinkling.stream.servlet.FormDataServlet;
import cn.twinkling.stream.servlet.Range;
import cn.twinkling.stream.servlet.StreamServlet;

/**
 * IO--closing, getting file name ... main function method
 */
public class IoUtil {
	static final Pattern RANGE_PATTERN = Pattern.compile("bytes \\d+-\\d+/\\d+");
	/** where the file should be put on. */
	public static final String REPOSITORY = System.getProperty("java.io.tmpdir", "/tmp/upload-repository");
	
	/**
	 * According the key, generate a file (if not exist, then create
	 * a new file).
	 * @param key
	 * @return
	 * @throws IOException
	 */
	public static File getFile(String key) throws IOException {
		return getFile(key, null);
	}
	
	/**
	 * According the key, generate a file (if not exist, then create
	 * a new file).
	 * @param key
	 * @param fullPath the file relative path(something like `a../bxx/wenjian.txt`)
	 * @return
	 * @throws IOException
	 */
	public static File getFile(String key, String fullPath) throws IOException {
		if (key == null || key.isEmpty())
			return null;
		String folder = "";
		if (fullPath != null && !fullPath.isEmpty()
				&& fullPath.indexOf("/") > 0) {
			int index = fullPath.lastIndexOf("/");
			folder = fullPath.substring(0, index).replaceAll("/", File.separator);
		}
		File f = new File(REPOSITORY + File.separator + folder + File.separator + key);
		if (!f.getParentFile().exists())
			f.getParentFile().mkdirs();
		if (!f.exists())
			f.createNewFile();
		
		return f;
	}

	/**
	 * Acquired the file.
	 * @param key
	 * @return
	 * @throws FileNotFoundException If key not found, will throws this.
	 */
	public static File getTokenedFile(String key) throws FileNotFoundException {
		if (key == null || key.isEmpty())
			return null;

		File f = new File(REPOSITORY + File.separator + key);
		if (!f.getParentFile().exists())
			f.getParentFile().mkdirs();
		if (!f.exists())
			throw new FileNotFoundException("File `" +f + "` not exist.");
		
		return f;
	}
	
	/**
	 * close the IO stream.
	 * @param stream
	 */
	public static void close(Closeable stream) {
		try {
			if (stream != null)
				stream.close();
		} catch (IOException e) {
		}
	}
	
	/**
	 * 获取Range参数
	 * @param req
	 * @return
	 * @throws IOException
	 */
	public static Range parseRange(HttpServletRequest req) throws IOException {
		String range = req.getHeader(StreamServlet.CONTENT_RANGE_HEADER);
		Matcher m = RANGE_PATTERN.matcher(range);
		if (m.find()) {
			range = m.group().replace("bytes ", "");
			String[] rangeSize = range.split("/");
			String[] fromTo = rangeSize[0].split("-");

			long from = Long.parseLong(fromTo[0]);
			long to = Long.parseLong(fromTo[1]);
			long size = Long.parseLong(rangeSize[1]);

			return new Range(from, to, size);
		}
		throw new IOException("Illegal Access!");
	}

	/**
	 * From the InputStream, write its data to the given file.
	 */
	public static long streaming(InputStream in, String key, String fileName) throws IOException {
		OutputStream out = null;
		long size = 0;
		try {
			File f = getFile(key);
			out = new FileOutputStream(f);

			int read = 0;
			final byte[] bytes = new byte[FormDataServlet.BUFFER_LENGTH];
			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			out.flush();
			/** rename the file */
			f.renameTo(getFile(fileName));
			
			size = getFile(fileName).length();
		} finally {
			close(out);
		}
		return size;
	}
}
最近下载更多
我真的是小明  LV10 2021年7月19日
hzszwx  LV1 2021年5月30日
yqd123456  LV3 2021年2月2日
maorchao  LV11 2020年11月19日
dzcdhj  LV4 2020年5月19日
1602749187  LV7 2020年4月15日
gaoleipro  LV2 2019年11月6日
killpofeng  LV5 2019年11月6日
kuiis66  LV1 2019年8月19日
skipple3  LV39 2019年8月3日
最近浏览更多
微信网友_6755417394941952 2023年11月28日
暂无贡献等级
yangk_126 2023年3月14日
暂无贡献等级
lemon1900 2022年9月6日
暂无贡献等级
xuexizhuanyong23  LV16 2022年8月7日
陈小灏  LV14 2022年6月1日
wanglinddad  LV54 2022年4月15日
zhjwgs  LV15 2022年2月22日
haoo123 2022年1月26日
暂无贡献等级
dfkk_love  LV11 2021年12月26日
15116483404  LV2 2021年12月3日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友