文件、文件流操作FileDataUtils类

package com.wjzh.info.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.io.ByteStreams;
/**
 * 文件转换工具类
 * @author niuchuang
 * @data 2018年12月14日
 */
public class FileDataUtils {
	
	private static final Logger log = LoggerFactory.getLogger(FileDataUtils.class);
	
	private static final String className = FileDataUtils.class.getName();
	
	public static final int CONNECT_TIMEOUT = 120000;//连接超时时间
	
	public static final String BM_ISO_8859_1 = "ISO-8859-1";
	
	public static final String BM_UTF_8 = "UTF-8";
	
	public static boolean isInputStream(InputStream input){
		byte[] bytes=null;
		if (input!=null) {
			try {
				bytes = ByteStreams.toByteArray(input);
			} catch (IOException e) {
				log.error(className,e);
				throw new RuntimeException(e);
			}finally{
				close(input);
			}
		}
		return (bytes!=null && bytes.length>0);
	}
	
	public static boolean isMultipartFile(MultipartFile multi){
		if (multi!=null) {
			InputStream is=null;
			try {
				is=multi.getInputStream();
				return isInputStream(is);
			} catch (IOException e) {
				return false;
			}finally{
				close(is);
			}
		}else{
			return false;
		}
	}
	public static String byteToString(byte[] bytes){
		try {
			if (bytes==null || bytes.length<=0) {
				throw new RuntimeException("bytes为空");
			}else{
				return new String(bytes, BM_ISO_8859_1);
			}
		} catch (Exception e) {
			log.error(className+".byteToString()",e);
			throw new RuntimeException("字节信息转换字符串失败",e);
		}
	}
	/**
	 * 指定路径下文件转换为字节
	 * @title
	 * @date 2018年12月5日
	 * @author niuchuang
	 * @param filePath
	 * @return
	 */
	public static byte[] getFilePathToBytes(String filePath) {
		byte[] data = null;
		/*
		File file = new File(filePath);
		if (file.exists()) {
			InputStream is=null;
			try {
				is=new FileInputStream(file);
				data=getInputStreamToBytes(is);
			} catch (Exception e) {
				log.error(className+".getFilePathToBytesString()",e);
				throw new RuntimeException(e);
			}finally{
				closeStream(is);
			}
		}*/
		if (StringUtils.isNotBlank(filePath)) {
			File file = new File(filePath);
			FileInputStream input=null;
			if (file.exists()) {
				try {
					input=new FileInputStream(file);
					data =getInputStreamToBytes(input);
				} catch (FileNotFoundException e) {
					log.error("",e);
					throw new RuntimeException(e);
				}
			}
		}
		return data;
	}
	public static byte[] getMultipartFileToBytes(MultipartFile wjxx){
		InputStream input=null;
		try {
			if (wjxx!=null) {
				input = wjxx.getInputStream();
			}else{
				throw new RuntimeException("文件内容为空");
			}
		} catch (Exception e) {
			log.error(className+".getMultipartFileToBytes()",e);
			throw new RuntimeException(e);
		}
		return getInputStreamToBytes(input);
	}
	public static byte[] getInputStreamToBytes(InputStream input){
		byte[] data = null;
		/*
		BufferedInputStream in = null;
		try {
			if (input!=null) {
				in = new BufferedInputStream(input);
				data = new byte[in.available()];
				in.read(data);
			}else{
				throw new RuntimeException("文件内容为空");
			}
		} catch (Exception e) {
			log.error(className+".getFilePathToBytesString()",e);
			throw new RuntimeException(e);
		}finally{
			closeStream(in);
			closeStream(input);
		}
		*/
		ByteArrayOutputStream swapStream =null;
		try {
			swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = input.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			data = swapStream.toByteArray();
		} catch (IOException e) {
			log.error("",e);
			throw new RuntimeException(e);
		}finally{
			close(swapStream);
			close(input);
		}
		return data;
	}
	/**
	 * 存储到本地磁盘
	 * @title
	 * @date 2018年11月22日
	 * @author niuchuang
	 * @param filePath
	 * @param file
	 * @return
	 */
	public static boolean createNewFile(byte[] fileContent,String newFilePath) {
		boolean b=false;
		BufferedOutputStream out = null;
		FileOutputStream outs = null;
		try {
			File newfile = new File(newFilePath);
			File parent = newfile.getParentFile();
			// 如果pdf保存路径不存在,则创建路径
			if (!parent.exists()) {
				parent.mkdirs();
			}
			outs=new FileOutputStream(newfile);
			out = new BufferedOutputStream(outs);
			if (!newfile.exists()) {
				newfile.createNewFile();
			}
			out.write(fileContent);
			out.flush();
			b=true;
		} catch (IOException e) {
			log.error(className+".createNewFile()",e);
			throw new RuntimeException(e);
		} finally {
			close(outs);
			close(out);
		}
		return b;
	}
	
	/**
	 * 生成文件信息
	 * @title
	 * @date 2018年12月5日
	 * @author niuchuang
	 * @param input
	 * @param newFilePath
	 * @return
	 */
	public static boolean createNewFile(InputStream input,String newFilePath){
		boolean b=false;
		OutputStream ous = null;
		try {
			File file1 = new File(newFilePath);
			File parent = file1.getParentFile();
			// 如果pdf保存路径不存在,则创建路径
			if (!parent.exists()) {
				parent.mkdirs();
			}
			file1.createNewFile();
			ous = new FileOutputStream(file1);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = input.read(buffer)) > -1) {
				ous.write(buffer, 0, len);
			}
			b=true;
		} catch (Exception e) {
			log.error(className+".createNewFile()",e);
			throw new RuntimeException(e);
		}finally {
			close(ous);
			close(input);
		}
		return b;
	}
	
	/**
	 * 生成文件信息(存在缺陷:生僻字乱码)
	 * @title
	 * @date 2018年12月5日
	 * @author niuchuang
	 * @param input
	 * @param newFilePath
	 * @deprecated
	 * @return
	 */
	public static boolean createNewFile2(InputStream input,String newFilePath){
		boolean b=false;
		OutputStreamWriter writer =null;
		InputStreamReader reader =null;
		OutputStream outStream=null;
		try {
			File file1 = new File(newFilePath);
			File parent = file1.getParentFile();
			// 如果pdf保存路径不存在,则创建路径
			if (!parent.exists()) {
				parent.mkdirs();
			}
			file1.createNewFile();
			reader = new InputStreamReader(input,"UTF-8");//读
			outStream=new FileOutputStream(file1);
			writer = new OutputStreamWriter(outStream,"UTF-8");//写
			
			char[] cs = new char[1024];//缓冲区
			int len = 0;
			while ((len = reader.read(cs)) > -1) {
				writer.write(cs , 0, len);//读几个写几个
				
			}
			b=true;
		} catch (Exception e) {
			log.error(className+".createNewFile()",e);
			throw new RuntimeException(e);
		}finally {
			close(reader);
			close(writer);
			close(outStream);
		}
		return b;
	}
	
	/**
	 * 内容读取	
	 * @title
	 * @date 2018年12月18日
	 * @author niuchuang
	 * @param file
	 * @return
	 */
	public static String readTxtFile(File file) {
		String lineTxt = null;
		StringBuffer content = new StringBuffer();
		if (file == null) {
			return "";
		}
		if (file.isFile() && file.exists()) { // 判断文件是否存在
			FileInputStream inoutStream=null;
			InputStreamReader read=null;
			BufferedReader bufferedReader =null;
			try {
				inoutStream=new FileInputStream(file);
				read = new InputStreamReader(inoutStream);// 考虑到编码格式
				bufferedReader = new BufferedReader(read);
				while ((lineTxt = bufferedReader.readLine()) != null) {
					content.append(lineTxt).append("\n");
				}
			} catch (Exception e) {
				log.error(className+".readTxtFile()",e);
				throw new RuntimeException(e);
			}finally {
				close(bufferedReader);
				close(read);
				close(inoutStream);
			}
		}
		return content.toString();
	}
	
	/**
	 * 获取文件名称
	 * @title
	 * @date 2018年12月17日
	 * @author niuchuang
	 * @param file
	 * @return
	 */
	public static String getFileName(MultipartFile file){
		boolean isWjxx=file!=null?isMultipartFile(file):false;
		String fileName=null;
		if (isWjxx) {
			fileName=file.getOriginalFilename();
			fileName=fileName.substring(0, fileName.lastIndexOf("."));
			
		}
		return fileName;
	}

	/**
	 * 关闭输出流
	 * 
	 * @param os
	 *            输出流
	 */
	public static void close(BufferedReader fs) {
		try {
			if (fs != null) {
				fs.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 关闭输出流
	 * 
	 * @param os
	 *            输出流
	 */
	public static void close(OutputStreamWriter os) {
		try {
			if (os != null) {
				os.flush();
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭输出流
	 * 
	 * @param os
	 *            输出流
	 */
	public static void close(ByteArrayOutputStream os) {
		try {
			if (os != null) {
				os.flush();
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭输出流
	 * 
	 * @title
	 * @date 2018年12月14日
	 * @author niuchuang
	 * @param os
	 */
	public static void close(BufferedOutputStream os) {
		try {
			if (os != null) {
				os.flush();
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭输出流
	 * 
	 * @param os
	 *            输出流
	 */
	public static void close(OutputStream os) {
		try {
			if (os != null) {
				os.flush();
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭输入流
	 * 
	 * @param is
	 *            输入流
	 */
	public static void close(ByteArrayInputStream is) {
		try {
			if (is != null) {
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭输出流
	 * 
	 * @param os
	 *            输出流
	 */
	public static void close(InputStreamReader fs) {
		try {
			if (fs != null) {
				fs.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭输入流
	 * 
	 * @param is
	 *            输入流
	 */
	public static void close(InputStream is) {
		try {
			if (is != null) {
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 判断URL是否可用
	 * @title
	 * @date 2018年12月28日
	 * @author niuchuang
	 * @param urlString
	 * @return
	 */
	public static boolean isUrlWith(String urlString) {
		boolean bool=false;
		long lo = System.currentTimeMillis();
		URL url;
		InputStream in=null;
		try {
			url = new URL(urlString);
			in = url.openStream();
			bool=true;
			
			log.info("连接可用");
		} catch (Exception e1) {
			log.info("连接打不开!");
		}finally{
			close(in);
			url = null;
		}
		return bool;
	}
	/**
	 * 判断URL是否可用
	 * @title
	 * @date 2018年12月28日
	 * @author niuchuang
	 * @param urlString
	 * @param timeOutMillSeconds
	 * @return
	 */
	public static boolean isUrlWithTimeOut(String urlString, int timeOutMillSeconds) {
		boolean bool=false;
		URL url;
		try {
			url = new URL(urlString);
			URLConnection co = url.openConnection();
			co.setConnectTimeout(timeOutMillSeconds);
			co.connect();
			bool=true;
			
			log.info("连接可用");
		} catch (Exception e1) {
			log.info("连接打不开!");
		}finally{
			url = null;
		}
		return bool;
	}
	
	/**
	 * 生成32位UUID,不含“-”符
	 * @return
	 */
	public static final String generateUUID(){
		String uuid = UUID.randomUUID().toString(); 
		return uuid.replaceAll("-", ""); 
	}
	
	public static final String getRequestId(){
		return generateUUID();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值