JAVA文件类工具
FileUtil
package cn.jiangzeyin.util.file;
import org.springframework.util.Assert;
import java.io.*;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.Properties;
/**
* 文件操作工具类
*
* @author jiangzeyin
*/
public final class FileUtil {
/**
* @param path path
* @return p
* @throws IOException io
* @author jiangzeyin
*/
public static Properties getProperties(String path) throws IOException {
Properties prop = new Properties();
InputStream in = new FileInputStream(path);
prop.load(in);
return prop;
}
/**
* 格式化单位
*
* @param size size
* @return str
*/
public static String getFormatSize(long size) {
double kiloByte = size / 1024;
if (kiloByte < 1) {
return size + "Byte";
}
double megaByte = kiloByte / 1024;
if (megaByte < 1) {
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
}
double gigaByte = megaByte / 1024;
if (gigaByte < 1) {
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
}
double teraBytes = gigaByte / 1024;
if (teraBytes < 1) {
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
}
BigDecimal result4 = new BigDecimal(teraBytes);
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
}
/**
* 判断文件是否存在
*
* @param path path
* @return boolean
*/
public static boolean exists(String path) {
File f = new File(path);
return f.exists();
}
/**
* 创建文件路径
*
* @param path path
* @return boolean
* @author jiangzeyin
*/
public static boolean mkdirs(String path) {
return mkdirs(new File(path), path.endsWith("/"));
}
/**
* @param file file
* @param isPath isPath
* @return boolean
* @author jiangzeyin
*/
public static boolean mkdirs(File file, boolean isPath) {
if (file == null)
return false;
if (isPath)
return file.mkdirs();
else
return file.getParentFile().mkdirs();
}
public static boolean mkdirs(File file) {
return mkdirs(file, false);
}
/**
* 读取文件全部内容
*
* @param file file
* @param encoding encoding
* @return str
* @throws IOException io
*/
public static String readToString(File file, String encoding) throws IOException {
BufferedReader br;
StringBuffer stringBuffer = null;
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
String line = null;
stringBuffer = new StringBuffer();
while ((line = br.readLine()) != null) {
stringBuffer.append(line);
}
br.close();
return stringBuffer.toString();// 返回文件内容,默认编码
}
public static String readToString(File file) throws IOException {
return readToString(file, "UTF-8");
}
public static String getFileEncode(String path) throws IOException {
String charset = "asci";
byte[] first3Bytes = new byte[3];
boolean checked = false;
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
bis.mark(0);
int read = bis.read(first3Bytes, 0, 3);
if (read == -1)
return charset;
if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
charset = "Unicode";// UTF-16LE
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
charset = "Unicode";// UTF-16BE
checked = true;
} else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) {
charset = "UTF8";
checked = true;
}
bis.reset();
if (!checked) {
while ((read = bis.read()) != -1) {
if (read >= 0xF0)
break;
if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
break;
if (0xC0 <= read && read <= 0xDF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF)
// 双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GB编码内
continue;
else
break;
} else if (0xE0 <= read && read <= 0xEF) { // 也有可能出错,但是几率较小
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF) {
charset = "UTF-8";
break;
} else
break;
} else
break;
}
}
// TextLogger.getLogger().info(loc + " " +
// Integer.toHexString(read));
}
bis.close();
return charset;
}
public static String readFile(String path) throws IOException {
// 判断文件是否存在
File file = new File(path);
if (!file.exists()) {
return null;
}
String data = null;
// 获取文件编码格式
String code = FileUtil.getFileEncode(path);
InputStreamReader isr = null;
// 根据编码格式解析文件
if ("asci".equals(code)) {
// 这里采用GBK编码,而不用环境编码格式,因为环境默认编码不等于操作系统编码
// code = System.getProperty("file.encoding");
code = "GBK";
}
isr = new InputStreamReader(new FileInputStream(file), code);
// 读取文件内容
int length = -1;
char[] buffer = new char[1024];
StringBuffer sb = new StringBuffer();
while ((length = isr.read(buffer, 0, 1024)) != -1) {
sb.append(buffer, 0, length);
}
data = new String(sb);
isr.close();
return data;
}
/**
* 读取文件
*
* @param fileName fileName
* @param encoding encoding
* @return strng
* @throws Exception e
* @author jiangzeyin
*/
public static String readToString(String fileName, String encoding) throws Exception {
File file = new File(fileName);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
return new String(filecontent, encoding);
}
/**
* 读取文件全部内容
* <p>
* 默认为UTF-8
*
* @param fileName fileName
* @return str
* @throws Exception e
* @author jiangzeyin
*/
public static String readToString(String fileName) throws Exception {
return readToString(fileName, "UTF-8");
}
/**
* 写文件
*
* @param fileName fileName
* @param content content
* @throws IOException io
* @author jiangzeyin
*/
public static void writeFile(String fileName, String content) throws IOException {
appendFileContext(fileName, content, false);
}
/**
* 添加文件内容
*
* @param fileName file
* @param content c
* @throws IOException io
* @author jiangzeyin
*/
public static void appendFileContext(String fileName, String content) throws IOException {
appendFileContext(fileName, content, true);
}
/**
* 追加文件内容
*
* @param fileName fileName
* @param content c
* @param append 是否是追加
* @throws IOException io
* @author jiangzeyin
*/
public static void appendFileContext(String fileName, String content, boolean append) throws IOException {
File file = new File(fileName);
file.getParentFile().mkdirs();
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
if (content != null)
out.write(content);
out.close();
}
public static boolean writeInputStream(InputStream inputStream, String path) throws IOException {
return writeInputStream(inputStream, new File(path));
} /**
* @param inputStream inp
* @param file file
* @return boolean
* @throws IOException io
*/
public static boolean writeInputStream(InputStream inputStream, File file) throws IOException {
Assert.notNull(inputStream);
Assert.notNull(file);
mkdirs(file);
DataOutputStream outputStream = null;
try {
outputStream = new DataOutputStream(new FileOutputStream(file));
int len = inputStream.available();
//判断长度是否大于1M
if (len <= 1024 * 1024) {
byte[] bytes = new byte[len];
inputStream.read(bytes);
outputStream.write(bytes);
} else {
int byteCount = 0;
//1M逐个读取
byte[] bytes = new byte[1024 * 1024];
while ((byteCount = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, byteCount);
}
}
} finally {
if (inputStream != null)
inputStream.close();
if (outputStream != null)
outputStream.close();
}
return true;
}
/**
* 判断流的字符串格式
*
* @param ins ins
* @return str
* @throws IOException io
*/
public static String getCharset(InputStream ins) throws IOException {
BufferedInputStream bin = new BufferedInputStream(ins);
int p = (bin.read() << 8) + bin.read();
String code = null;
switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
default:
code = "GBK";
}
ins.close();
bin.close();
return code;
}
/**
* 获取文件 编码
*
* @param fileName fileName
* @return str
* @throws IOException io
* @author jiangzeyin
*/
public static String getFileCharset(String fileName) throws IOException {
FileInputStream ins = new FileInputStream(fileName);
return getCharset(ins);
} public static String getFilePath(String path) {
File file = new File(path);
return getFilePath(file);
}
public static String getFilePath(File file) {
return clearPath(file.getParent());
}
/**
* 获取文件后缀
*
* @param filename file
* @return str
* @author jiangzeyin
*/
public static String getFileExt(String filename) {
String ext = "";
int index = filename.lastIndexOf(".");
if (index == -1) {
return "";
}
ext = filename.substring(index + 1);
return ext;
}
public static String clearPath(String input) {
input = input.replace('\\', '/');
return clearPath_(input);
}
/**
* 获取文件名
*
* @param filename file
* @return s
* @author jiangzeyin
*/
public static String getFileName(String filename) {
String ext = "";
int index = filename.lastIndexOf("/");
if (index == -1) {
return filename;
}
ext = filename.substring(index + 1);
return ext;
}
private static String clearPath_(String input) {
int from = 0;
int j = input.indexOf("://");
if (j != -1) {
from = j + 3;
}
int i = input.indexOf("//", from);
if (i == -1) {
return input;
}
String input_ = input.substring(0, i) + "/" + input.substring(i + 2);
return clearPath_(input_);
}
/**
* 递归删除目录下的所有文件及子目录下所有文件
*
* @param dir 将要删除的文件目录
* @return boolean Returns "true" if all deletions were successful. If a
* deletion fails, the method stops attempting to delete and returns
* "false".
*/
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
// 递归删除目录中的子目录下
for (int i = 0; i < (children != null ? children.length : 0); i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
/**
* 获取指定目录下的所有文件
*
* @param path path
* @return LinkedList
* @author XiangZhongBao
*/
public static LinkedList<File> getFolderFiles(String path) {
File file = new File(path);
if (!file.exists())
return null;
if (!file.isDirectory())
return null;
File[] files = file.listFiles();
if (files == null)
return null;
LinkedList<File> linkedList = new LinkedList<>();
for (File item : files) {
if (item.isDirectory()) {
LinkedList<File> tempFile = getFolderFiles(item.getPath());
if (tempFile != null)
linkedList.addAll(tempFile);
} else {
linkedList.add(item);
}
}
return linkedList;
}
/**
* @param dir dir
* @return boolean
* @author jiangzeyin
*/
public static boolean deleteDir(String dir) {
return deleteDir(new File(dir));
}
}
FileType
package cn.jiangzeyin.util.file;
/**
* Created by jiangzeyin on 2017/3/15.
*/
public enum FileType {
/**
* JPEG
*/
JPEG("FFD8FF", "jpg"),
/**
* PNG
*/
PNG("89504E47", "png"),
/**
* GIF
*/
GIF("47494638", "gif"),
/**
* TIFF
*/
TIFF("49492A00"),
/**
* Windows bitmap
*/
BMP("424D"),
/**
* CAD
*/
DWG("41433130"),
/**
* Adobe photoshop
*/
PSD("38425053"),
/**
* Rich Text Format
*/
RTF("7B5C727466"),
/**
* XML
*/
XML("3C3F786D6C"),
/**
* HTML
*/
HTML("68746D6C3E"),
/**
* Outlook Express
*/
DBX("CFAD12FEC5FD746F "),
/**
* Outlook
*/
PST("2142444E"),
/**
* doc;xls;dot;ppt;xla;ppa;pps;pot;msi;sdw;db
*/
OLE2("0xD0CF11E0A1B11AE1"),
/**
* Microsoft Word/Excel
*/
XLS_DOC("D0CF11E0"),
/**
* Microsoft Access
*/
MDB("5374616E64617264204A"),
/**
* Word Perfect
*/
WPB("FF575043"),
/**
* Postscript
*/
EPS_PS("252150532D41646F6265"),
/**
* Adobe Acrobat
*/
PDF("255044462D312E"),
/**
* Windows Password
*/
PWL("E3828596"),
/**
* ZIP Archive
*/
ZIP("504B0304"),
/**
* ARAR Archive
*/
RAR("52617221"),
/**
* WAVE
*/
WAV("57415645"),
/**
* AVI
*/
AVI("41564920"),
/**
* Real Audio
*/
RAM("2E7261FD"),
/**
* Real Media
*/
RM("2E524D46"),
/**
* Quicktime
*/
MOV("6D6F6F76"),
/**
* Windows Media
*/
ASF("3026B2758E66CF11"),
/**
* MIDI
*/
MID("4D546864");
private String value = "";
private String ext = "";
FileType(String value) {
this.value = value;
}
FileType(String value, String ext) {
this(value);
this.ext = ext;
}
public String getExt() {
return ext;
}
public String getValue() {
return value;
}
}
FileStreamUtil
package cn.jiangzeyin.util;
import cn.jiangzeyin.util.file.FileType;
import org.springframework.util.Assert;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by jiangzeyin on 2017/3/15.
*/
public abstract class FileStreamUtil {
/**
* 复制Input流
*
* @param input inp
* @return inp
* @throws Exception e
* @author jiangzeyin
*/
public static InputStream copyInputStream(InputStream input) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
//input = new ByteArrayInputStream(baos.toByteArray());
InputStream stream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
return stream;
}
/**
* @param is is
* @return fileType
* @throws IOException io
* @author jiangzeyin
*/
public static FileType getFileType(InputStream is) throws IOException {
Assert.notNull(is);
byte[] src = new byte[28];
is.read(src, 0, 28);
StringBuilder stringBuilder = new StringBuilder("");
if (src.length <= 0) {
return null;
}
for (byte aSrc : src) {
int v = aSrc & 0xFF;
String hv = Integer.toHexString(v).toUpperCase();
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
//System.out.println(stringBuilder);
FileType[] fileTypes = FileType.values();
for (FileType fileType : fileTypes) {
if (stringBuilder.toString().startsWith(fileType.getValue())) {
return fileType;
}
}
return null;
}
}
JAVA文件类工具的更多相关文章
- java文件处理工具类
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedRead ...
- 在线数据库表(sql语句)生成java实体类工具
相信每个做java开发的读者,都接触过SQL建表语句,尤其是在项目开发初期,因为数据库是项目的基石. 在现代项目开发中,出现了许多ORM框架,通过简单的实体映射,即可实现与数据库的交互,然而我们最初设 ...
- java 文件类 null与exists()是不一样的
java 文件类 null与exists()是不一样的File imageFile0A=null; (imageFile0A==null)与!imageFile0A.exists() 不等价! 一个文 ...
- Java 文件切割工具类
Story: 发送MongoDB 管理软件到公司邮箱,工作使用. 1.由于公司邮箱限制附件大小,大文件无法发送,故做此程序用于切割大文件成多个小文件,然后逐个发送. 2.收到小文件之后,再重新组合成原 ...
- java文件对照工具
今天想比較一下两个java文件.这两个文件是本地的. 就在网上下载了一个对照工具(破解版)认为挺好用的对于不同的地方有高亮显示. 就给大家分享一下.软件名叫:beyond compare 软件下载地址 ...
- Java文件类型工具类
package *; import java.util.HashMap; import java.util.Map; /** * <p> * <b>FileTypeEnum2& ...
- java文件读写工具类
依赖jar:commons-io.jar 1.写文件 // by FileUtilsList<String> lines = FileUtils.readLines(file, " ...
- java 文件类操作(转载)
11.3 I/O类使用 由于在IO操作中,需要使用的数据源有很多,作为一个IO技术的初学者,从读写文件开始学习IO技术是一个比较好的选择.因为文件是一种常见的数据源,而且读写文件也是程序员进行IO编程 ...
- Java 文件类 File
1.File 类 1.File 类 1.1.构造方法 文件的 抽象路径名(操作系统无关) 构造方法 格式 说明 File(String filename) 把文件路径名字符串转换为“抽象路径名”,用来 ...
随机推荐
- C++入门经典-例6.21-比较string字符串,比较两个字符串
1:使用“>”.“!=”.“>=”等比较运算符可以比较两个字符串的内容.比较的方法是将两个string字符串从头开始比较每一个字符,直到出现两者不一致.比较这两个不相同的字符的字面值,得出 ...
- 解决分页插件ClassNotFoundException: org.springframework.boot.bind.RelaxedPropertyResolver
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.github.p ...
- 20165207 Exp9 Web安全基础
目录 20165207 Exp9 Web安全基础 一.实验过程 1.环境配置 2.代理工具burpsuite 2.1 Http proxies -> Use the intercept 3.sq ...
- 打开下载CA root 证书的链接失败
下载CA root 证书 http://adip/certsrv server error or refuse to connect 这是由于AD上没有安装Active Directory Certi ...
- Java-JVM 栈帧(Stack Frame)
一.概述 栈帧位置 JVM 执行 Java 程序时需要装载各种数据到内存中,不同的数据存放在不同的内存区中(逻辑上),这些数据内存区称作运行时数据区(Run-Time Data Areas). 其中 ...
- SV服务器
什么是服务端? 就是安装了服务端软件的电脑 下载 VisualSVN是一款图形化svn服务器. 官 网: http://www.visualsvn.com/server/ 下载地址: http://w ...
- SELECT * 测试
描述 大家通常禁止在生产环境直接使用select * 已成常识了,也常常在开发规范中就会规定不允许直接使用select *,那么我们为什么不允许使用select * ,在一些什么场景下select * ...
- dockerfile中配置时区
https://www.cnblogs.com/kevingrace/p/5570597.html #设置时区RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai ...
- IFC布局特点
IFC(inline formatting context),行内格式化上下文 特点: 1.内联元素在水平线上一个接一个排列 2.内部元素水平方向上的margin.padding.border有效,垂 ...
- Go package(2) strings 用法
go version go1.10.3 Go中的字符串用法,可以在 godoc.org 上查看语法和用法. 最简单的语法就是获取字符串中的子串 s := "hello world" ...