首页>代码>Java版FastDFS文件服务器,springmvc做的集成>/fastdfs-fileserver/src/main/java/hello/world/fileserver/tools/FileUtil.java
package hello.world.fileserver.tools;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
/**
 * 
 * @author 宋健
 * 
 * qq 1738042258
 */
public class FileUtil {

	/*
	 * 根据uploadKey得到断点续传的文件名
	 */
	public static String getFileNameFsFileUploadKey(String uploadKey) {
		return "fileName";
	}

	/*
	 * 新建一个文件名
	 */
	public static String newFullfilename(Integer uid, String tag, String suffix) {
		return null;
	}

	/**
	 * 保存文件流信息
	 * 
	 * @param fullfilename
	 * @param in
	 * @return
	 */
	public static boolean save(String fullfilename, InputStream in, Integer dataLen) {
		boolean result = false;
		if (fullfilename == null || in == null) {
			return result;
		}
		FileOutputStream out = null;
		try {
			File file = new File(fullfilename);
			if (file.exists()) {
				file.delete();
			}
			out = new FileOutputStream(file, true);
			byte[] buf = new byte[1024];
			int size;
			int dataLength = 0;
			while ((size = in.read(buf)) > 0) {
				out.write(buf, 0, size);
				dataLength += size;
			}
			out.flush();
			out.close();
			in.close();

			if (dataLength == dataLen) {
				result = true;
			} else {
				Logit.error("fullfilename(" + fullfilename + ")'offset/max is invalid!");
			}
		} catch (Exception e) {
			Logit.error(e.getMessage(), new Throwable(e));
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception eo) {
				Logit.error(eo.getMessage(), new Throwable(eo));
			}
		}
		return result;
	}

	/**
	 * 合并文件
	 * 
	 * @param filePath
	 * @param filechunkcount
	 * @param uploadKey
	 * @param suffix
	 * @param uid
	 * @return
	 */
	public String mergeFile(String filePath, int filechunkcount, String uploadKey, String suffix, Integer uid) {
		FileOutputStream out = null;
		try {
			String filename = filePath + uploadKey + suffix;
			File file = new File(filename);
			if (file.exists()) {
				file.delete();
			}
			out = new FileOutputStream(file, true);
			for (int i = 1; i <= filechunkcount; i++) {
				try {
					Logit.error("FormUpload 用户ID " + uid + " uploadfile 合并文件 " + filePath + uploadKey + "_" + i);
					FileInputStream input = new FileInputStream(filePath + uploadKey + "_" + i);
					byte[] b = new byte[4096];
					int nRead;
					while ((nRead = input.read(b, 0, 4096)) != -1) {
						write(out, b, 0, nRead, uid);
					}
					input.close();
				} catch (Exception e) {
					Logit.error("FormUpload 用户ID " + uid + " " + e.getMessage(), new Throwable(e));
				}
			}
			out.close();
			return filename;
		} catch (Exception e) {
			Logit.error("FormUpload 用户ID " + uid + " " + e.getMessage(), new Throwable(e));
			return null;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception eo) {
				Logit.error(eo.getMessage(), new Throwable(eo));
			}
		}
	}

	/**
	 * 写文件
	 * 
	 * @param b
	 * @param nStart
	 * @param nLen
	 * @return
	 */
	private static int write(FileOutputStream out, byte[] b, int nStart, int nLen, Integer uid) {
		int n = -1;
		try {
			out.write(b, nStart, nLen);
			n = nLen;
		} catch (IOException e) {
			Logit.error("FormUpload 用户ID " + uid + " " + e.getMessage(), new Throwable(e));
		}
		return n;
	}

	/**
	 * 保存字节流
	 * 
	 * @param fullfilename
	 * @param bytes
	 * @return
	 */
	public static boolean save(String fullfilename, byte[] bytes) {
		boolean result = false;

		if (fullfilename == null || bytes == null || bytes.length == 0) {
			return result;
		}

		try {
			RandomAccessFile out = new RandomAccessFile(fullfilename, "rw");
			out.seek(0);
			out.write(bytes, 0, bytes.length);

			out.close();

			result = true;
		} catch (Exception e) {
			Logit.error(e.getMessage(), new Throwable(e));
		}

		return result;
	}
 
	/**
	 * 获取文件的md5 信息
	 * 
	 * @param fullfilename
	 * @return
	 */
	public static String md5(String path) {
		String result = "";
		if (StringUtils.isBlank(path)) {
			Logit.error("dsMountPath/filefullname is null!");
			return result;
		}
		BufferedReader br = null;
		Process process = null;
		try {
			String APP_MD5 = null;

			Properties props = System.getProperties(); // 获得系统属性集
			String osName = props.getProperty("os.name");
			if (osName.startsWith("Linux")) {
				APP_MD5 = "([^\\s]*)[\\s*]*([^\\s]*)";
				process = Runtime.getRuntime().exec("md5sum " + path);
			} else if (osName.startsWith("Mac")) {
				APP_MD5 = "([^=]*)=[\\s*]*([^=]*)";
				process = Runtime.getRuntime().exec("md5 " + path);
			} else {
				Logit.error(osName + " is invalid!");
				return result;
			}

			br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;

			List<String> tmpList = new ArrayList<String>();
			while ((line = br.readLine()) != null) {
				tmpList.add(line);
			}

			StringBuffer sbinfo = new StringBuffer();
			for (String info : tmpList) {
				sbinfo.append(info);
				sbinfo.append("\n");
			}

			// 解析md5值
			Pattern p = Pattern.compile(APP_MD5, Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(sbinfo.toString());
			while (m.find()) {
				try {
					if (osName.startsWith("Linux")) {
						result = m.group(1).trim();
					} else if (osName.startsWith("Mac")) {
						result = m.group(2).trim();
					}
					break;
				} catch (Exception e) {
					Logit.error(e.getMessage(), new Throwable(e));
				}
			}
		} catch (Exception e) {
			Logit.error(e.getMessage(), new Throwable(e));
		} finally {
			if (process != null) {
				process.destroy();
			}
			if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					Logit.error(e.getMessage(), new Throwable(e));
				}
			}
		}
		return result;
	}

	/**
	 * 删除文件 对于图片则将水印文件删除
	 * 
	 * @param dsMountPath
	 * @param filename
	 * @return
	 */
	public static boolean delete(String dsMountPath, String filename) {
		boolean result = false;

		if (dsMountPath == null || filename == null) {
			Logit.error("dsMountPath/filename is null!");
			return result;
		}

		StringBuffer sb = new StringBuffer(dsMountPath);
		if (!dsMountPath.endsWith(File.separator)) {
			sb.append(File.separator);
		}

		sb.append(filename);

		// 如果是图片类,则删除水印功能。
		Process process = null;
		BufferedReader br = null;
		try {
			Properties props = System.getProperties(); // 获得系统属性集
			String osName = props.getProperty("os.name");
			if (osName.startsWith("Linux") || osName.startsWith("Mac")) {
				String suffix = "";
				int pos = filename.lastIndexOf(".");
				if (pos > 0) {
					suffix = filename.substring(pos);
				}
				boolean haswm = true;
				String fullfilename = sb.toString();
				if (haswm) {
					String fullfilenamewm = null;
					if (StringUtils.isBlank(suffix)) {
						fullfilenamewm = fullfilename + "wm";
					} else {
						pos = fullfilename.lastIndexOf(".");
						fullfilenamewm = fullfilename.substring(0, pos) + "wm" + suffix;
					}
					process = Runtime.getRuntime().exec("rm -rf " + fullfilename + " " + fullfilenamewm);
				} else {
					process = Runtime.getRuntime().exec("rm -rf " + fullfilename);
				}
			} else {
				String fullfilename = sb.toString();
				File f = new File(fullfilename);
				f.delete();
				// Logit.error(osName + " is invalid!");
				return true;
			}
			br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			while ((br.readLine()) != null) {
				continue;
			}
			result = true;
		} catch (Exception e) {
			Logit.error(e.getMessage(), new Throwable(e));
		} finally {
			if (process != null) {
				process.destroy();
			}
			if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					Logit.error(e.getMessage(), new Throwable(e));
				}
			}
		}

		return result;
	}

	/**
	 * 将HTTP资源另存为文件
	 * 
	 * @param sourceUrl
	 * @param savefilepath
	 * @return
	 */
	@SuppressWarnings("unused")
	public static boolean saveToFileByUrl(String sourceUrl, String savefilepath) {
		boolean result = false;

		if (!sourceUrl.startsWith("http://") && !sourceUrl.startsWith("https://") && !sourceUrl.startsWith("ftp://")) {
			return result;
		}

		if (savefilepath == null) {
			Logit.error("savefilepath is null!");
			return result;
		}

		// 获取url扩展名
		String ext = null;
		int extindex = sourceUrl.lastIndexOf(".");
		if (extindex > 0) {
			ext = sourceUrl.substring(extindex);
		} else {
			Logit.error("ext is null!");
			return result;
		}

		FileOutputStream fos = null;
		HttpURLConnection httpUrl = null;
		DataInputStream in = null;

		try {

			URL url = null;
			byte[] buf = new byte[1024];
			int size = 0;

			// 建立链接
			url = new URL(sourceUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.setConnectTimeout(30000);
			httpUrl.setReadTimeout(30000);

			// 连接指定的资源
			httpUrl.connect();

			// 获取网络输入流
			in = new DataInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(savefilepath);

			while ((size = in.read(buf)) != -1)
				fos.write(buf, 0, size);

			in.close();
			fos.close();

			result = true;
		} catch (Exception ex) {
			Logit.error("App.sourceUrl:" + sourceUrl + "; message:" + ex.getMessage(), new Throwable(ex));
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
				} finally {
					in = null;
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				} finally {
					fos = null;
				}
			}
			if (httpUrl != null) {
				httpUrl.disconnect();
			}
		}

		return result;
	} 

	/**
	 * 获取size长度的随机码。
	 * 
	 * @param size
	 * @return
	 */
	public static String randomCode(int size) {
		String[] number = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "A", "B", "C", "D", "E", "F",
				"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
				"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
				"w", "x", "y", "z" };

		Random rnd = new Random();
		int p = number.length - 1;

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < size; i++) {
			int j = rnd.nextInt(p) + 1;
			sb.append(number[j]);
		}
		return sb.toString();
	}

	/**
	 * 字节转16进制
	 * 
	 * @param bytes
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String bytes2hex01(byte[] bytes) {
		/**
		 * 第一个参数的解释,记得一定要设置为1 signum of the number (-1 for negative, 0 for zero,
		 * 1 for positive).
		 */
		BigInteger bigInteger = new BigInteger(1, bytes);
		return bigInteger.toString(16);
	}

	public static void delete(File file) {
		try {
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
		}
	}

	public static void delete(String filePath) {
		File file = new File(filePath);
		try {
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
		}
	}

	public static long getLength(String filePath) {
		File file = new File(filePath);
		try {
			if (file.exists()) {
				return file.length();
			}
		} catch (Exception e) {
		}
		return 0;
	}
}
最近下载更多
1529860026  LV24 2023年6月1日
lris_luanling  LV11 2021年1月22日
simple丶余心  LV21 2020年9月26日
lwp011  LV27 2020年7月7日
王可以  LV10 2020年4月22日
442529474  LV6 2020年3月11日
whtfj  LV2 2019年9月6日
huangxing11111  LV1 2019年8月6日
yanghanqiang  LV3 2019年7月5日
liujiaweijv  LV7 2019年7月5日
最近浏览更多
interface  LV22 8月10日
1529860026  LV24 2023年6月1日
240598911  LV10 2021年10月25日
axj52520  LV1 2021年9月5日
503382513  LV10 2021年4月16日
liqinwyyx  LV6 2021年3月24日
yiposhop  LV4 2021年1月22日
lris_luanling  LV11 2021年1月21日
0592lyj  LV9 2021年1月19日
dongzhan  LV12 2020年12月22日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友