java_io_操作封装
package com.wiker; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; /**
* @author Wiker Yong Email:<a href="mailto:wikeryong@gmail.com">wikeryong@gmail.com</a>
* @date 2013-11-8 下午6:21:45
* @version 1.0-SNAPSHOT
*/
@SuppressWarnings("resource")
public class FileUtils { /**
* 获取文件MD5值
*
* @param file
* @return
*/
public static String getMd5ByFile(File file) {
String value = null;
FileInputStream in = null;
try {
in = new FileInputStream(file);
MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, ,
file.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteBuffer);
BigInteger bi = new BigInteger(, md5.digest());
value = bi.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
} /**
* 获取文件大小
*
* @param file
* @return
*/
public static long getFileLength(File file)
throws IOException {
FileInputStream fis = null;
fis = new FileInputStream(file);
return fis.available();
} /**
* 读取文件到二进制
*
* @author WikerYong Email:<a href="#">yw_312@foxmail.com</a>
* @version 2012-3-23 上午11:47:06
* @param file
* @return
* @throws IOException
*/
public static byte[] getBytesFromFile(File file)
throws IOException {
InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) {
// File is too large
} byte[] bytes = new byte[(int) length]; // Read in the bytes
int offset = ;
int numRead = ;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= ) {
offset += numRead;
} // Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("不能读取文件: " + file.getName());
} is.close();
return bytes;
} /**
* 获取标准文件大小,如30KB,15.5MB
*
* @param file
* @return
* @throws IOException
*/
public static String getFileSize(File file)
throws IOException {
long size = getFileLength(file);
DecimalFormat df = new DecimalFormat("###.##");
float f;
if (size < * ) {
f = (float) ((float) size / (float) );
return (df.format(new Float(f).doubleValue()) + " KB");
} else {
f = (float) ((float) size / (float) ( * ));
return (df.format(new Float(f).doubleValue()) + " MB");
} } /**
* 复制文件
*
* @param f1
* 源文件
* @param f2
* 目标文件
* @throws Exception
*/
public static void copyFile(File f1, File f2)
throws Exception {
int length = ;
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
FileChannel inC = in.getChannel();
FileChannel outC = out.getChannel();
ByteBuffer b = null;
while (true) {
if (inC.position() == inC.size()) {
inC.close();
outC.close();
}
if ((inC.size() - inC.position()) < length) {
length = (int) (inC.size() - inC.position());
} else
length = ;
b = ByteBuffer.allocateDirect(length);
inC.read(b);
b.flip();
outC.write(b);
outC.force(false);
}
} /**
* 检查文件是否存在
*
* @param fileName
* @return
* @throws IOException
*/
public static boolean existFile(String fileName)
throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new IOException("文件未找到:" + fileName);
}
return file.exists();
} /**
* 删除文件
*
* @param fileName
*/
public static void deleteFile(String fileName)
throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new IOException("文件未找到:" + fileName);
}
file.delete();
} /**
* 读取文件到字符串
*
* @param fileName
* @return
* @throws IOException
*/
public static String readFile(String fileName)
throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new IOException("文件未找到:" + fileName);
} BufferedReader in = new BufferedReader(new FileReader(file));
StringBuffer sb = new StringBuffer();
String str = "";
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
} /**
* 获取目录所有所有文件和文件夹
*
* @param fileName
* @return
* @throws IOException
*/
public static List<File> listFiles(String fileName)
throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new IOException("文件未找到:" + fileName);
}
return Arrays.asList(file.listFiles());
} /**
* 创建目录
*
* @param dir
*/
public static void mkdir(String dir) {
String dirTemp = dir;
File dirPath = new File(dirTemp);
if (!dirPath.exists()) {
dirPath.mkdir();
}
} /**
* 新建文件
*
* @param fileName
* String 包含路径的文件名 如:E:\phsftp\src\123.txt
* @param content
* String 文件内容
*/
public static void createNewFile(String fileName, String content)
throws IOException {
String fileNameTemp = fileName;
File filePath = new File(fileNameTemp);
if (!filePath.exists()) {
filePath.createNewFile();
}
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
String strContent = content;
pw.println(strContent);
pw.flush();
pw.close();
fw.close(); } /**
* 删除文件夹
*
* @param folderPath
* 文件夹路径
*/
public static void delFolder(String folderPath) {
// 删除文件夹里面所有内容
delAllFile(folderPath);
String filePath = folderPath;
java.io.File myFilePath = new java.io.File(filePath);
// 删除空文件夹
myFilePath.delete();
} /**
* 删除文件夹里面的所有文件
*
* @param path
* 文件夹路径
*/
public static void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] childFiles = file.list();
File temp = null;
for (int i = ; i < childFiles.length; i++) {
// File.separator与系统有关的默认名称分隔符
// 在UNIX系统上,此字段的值为'/';在Microsoft Windows系统上,它为 '\'。
if (path.endsWith(File.separator)) {
temp = new File(path + childFiles[i]);
} else {
temp = new File(path + File.separator + childFiles[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + File.separatorChar + childFiles[i]);// 先删除文件夹里面的文件
delFolder(path + File.separatorChar + childFiles[i]);// 再删除空文件夹
}
}
} /**
* 复制单个文件,传统方式
*
* @param srcFile
* 包含路径的源文件 如:E:/phsftp/src/abc.txt
* @param dirDest
* 目标文件目录;若文件目录不存在则自动创建 如:E:/phsftp/dest
* @throws IOException
*/
public static void copyFile(String srcFile, String dirDest)
throws IOException {
FileInputStream in = new FileInputStream(srcFile);
mkdir(dirDest);
FileOutputStream out = new FileOutputStream(dirDest + "/" + new File(srcFile).getName());
int len;
byte buffer[] = new byte[];
while ((len = in.read(buffer)) != -) {
out.write(buffer, , len);
}
out.flush();
out.close();
in.close();
} /**
* 复制文件夹
*
* @param oldPath
* String 源文件夹路径 如:E:/phsftp/src
* @param newPath
* String 目标文件夹路径 如:E:/phsftp/dest
* @return boolean
*/
public static void copyFolder(String oldPath, String newPath)
throws IOException {
// 如果文件夹不存在 则新建文件夹
mkdir(newPath);
File file = new File(oldPath);
String[] files = file.list();
File temp = null;
for (int i = ; i < files.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + files[i]);
} else {
temp = new File(oldPath + File.separator + files[i]);
} if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/"
+ (temp.getName()).toString());
byte[] buffer = new byte[ * ];
int len;
while ((len = input.read(buffer)) != -) {
output.write(buffer, , len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);
}
}
} /**
* 移动文件到指定目录
*
* @param oldPath
* 包含路径的文件名 如:E:/phsftp/src/ljq.txt
* @param newPath
* 目标文件目录 如:E:/phsftp/dest
*/
public static void moveFile(String oldPath, String newPath)
throws IOException {
copyFile(oldPath, newPath);
deleteFile(oldPath);
} /**
* 移动文件到指定目录,不会删除文件夹
*
* @param oldPath
* 源文件目录 如:E:/phsftp/src
* @param newPath
* 目标文件目录 如:E:/phsftp/dest
*/
public static void moveFiles(String oldPath, String newPath)
throws IOException {
copyFolder(oldPath, newPath);
delAllFile(oldPath);
} /**
* 移动文件到指定目录,会删除文件夹
*
* @param oldPath
* 源文件目录 如:E:/phsftp/src
* @param newPath
* 目标文件目录 如:E:/phsftp/dest
*/
public static void moveFolder(String oldPath, String newPath)
throws IOException {
copyFolder(oldPath, newPath);
delFolder(oldPath);
} /**
* 解压zip文件
* 说明:本程序通过ZipOutputStream和ZipInputStream实现了zip压缩和解压功能.
* 问题:由于java.util.zip包并不支持汉字,当zip文件中有名字为中文的文件时,
* 就会出现异常:"Exception in thread "main " java.lang.IllegalArgumentException
* at java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285)
* @param srcDir
* 解压前存放的目录
* @param destDir
* 解压后存放的目录
* @throws Exception
*/
public static void unZip(String srcDir, String destDir)
throws IOException {
int leng = ;
byte[] b = new byte[ * ];
/** 获取zip格式的文件 **/
File[] zipFiles = new ExtensionFileFilter("zip").getFiles(srcDir);
if (zipFiles != null && !"".equals(zipFiles)) {
for (int i = ; i < zipFiles.length; i++) {
File file = zipFiles[i];
/** 解压的输入流 * */
ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
File destFile = null;
if (destDir.endsWith(File.separator)) {
destFile = new File(destDir + entry.getName());
} else {
destFile = new File(destDir + File.separator + entry.getName());
}
/** 把解压包中的文件拷贝到目标目录 * */
FileOutputStream fos = new FileOutputStream(destFile);
while ((leng = zis.read(b)) != -) {
fos.write(b, , leng);
}
fos.close();
}
zis.close();
}
}
} /**
* 压缩文件
* 说明:本程序通过ZipOutputStream和ZipInputStream实现了zip压缩和解压功能.
* 问题:由于java.util.zip包并不支持汉字,当zip文件中有名字为中文的文件时,
* 就会出现异常:"Exception in thread "main " java.lang.IllegalArgumentException
* at java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285)
* @param srcDir
* 压缩前存放的目录
* @param destDir
* 压缩后存放的目录
* @throws Exception
*/
public static void zip(String srcDir, String destDir)
throws IOException {
String tempFileName = null;
byte[] buf = new byte[ * ];
int len;
// 获取要压缩的文件
File[] files = new File(srcDir).listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
if (destDir.endsWith(File.separator)) {
tempFileName = destDir + file.getName() + ".zip";
} else {
tempFileName = destDir + File.separator + file.getName() + ".zip";
}
FileOutputStream fos = new FileOutputStream(tempFileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);// 压缩包 ZipEntry ze = new ZipEntry(file.getName());// 压缩包文件名
zos.putNextEntry(ze);// 写入新的ZIP文件条目并将流定位到条目数据的开始处 while ((len = bis.read(buf)) != -) {
zos.write(buf, , len);
zos.flush();
}
bis.close();
zos.close(); }
}
}
} /**
* 读取数据
*
* @param inSream
* @param charsetName
* @return
* @throws Exception
*/
public static String readData(InputStream inSream, String charsetName)
throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[];
int len = -;
while ((len = inSream.read(buffer)) != -) {
outStream.write(buffer, , len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
} public static boolean rename(String srcPath,String destPath){
//被移动的文件夹
File file = new File(srcPath);
//目标文件夹
File dir = new File(destPath);
//将文件移动到另一个文件目录下
boolean success = file.renameTo(dir);
return success;
} /**
* 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码
*
* @param path
* @return
* @throws Exception
*/
public static Set<String> readFileLine(String path)
throws IOException {
Set<String> datas = new HashSet<String>();
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
datas.add(line);
}
br.close();
fr.close();
return datas;
} public static String getExtensionExclude(String filepath){ int idx = filepath.lastIndexOf(".");
if (idx == -) {
return "";
} else if (idx == filepath.length() - ) {
return "";
} else {
return filepath.substring(,idx);
}
} public static void main(String[] args) {
try {
unZip("c:/test", "c:/test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } class ExtensionFileFilter
implements FileFilter { private String extension; public ExtensionFileFilter(String extension) {
this.extension = extension;
} public File[] getFiles(String srcDir) throws IOException {
return (File[]) FileUtils.listFiles(srcDir).toArray();
} public boolean accept(File file) {
if (file.isDirectory()) {
return false;
} String name = file.getName();
// find the last
int idx = name.lastIndexOf(".");
if (idx == -) {
return false;
} else if (idx == name.length() - ) {
return false;
} else {
return this.extension.equals(name.substring(idx + ));
}
} }
java_io_操作封装的更多相关文章
- MFC--串口编程---WIN API的方式将串扣操作封装在线程类中
串口采集数据 本文档介绍的是如何获取串口原始数据并将原始数据解析成可处理或可展示的数据. 一.串口采集有很多方式: 1).MFC有一个专门的控件,直接编程采集,一个控件只能采集一个串口,而且串口名字比 ...
- 【小结】有关mysql扩展库和mysqli扩展库的crud操作封装
现阶段php如果要操作mysql数据库 php给我们提供了3套库 1.mysql扩展库 面向过程操作 2.mysqli扩展库 面向对象操作和面向过程操作并存 安全性和效率高于mysql扩展库 ...
- JDBC操作封装
这两天学习了一下jdbc的封装,依据的是下面这篇 http://wenku.baidu.com/link?url=FaFDmQouYkKO24ApATHYmA5QzUcj-UE-7RSSZaBWPqk ...
- C# .NET更智能的数据库操作封装项目
前面两篇文章介绍了框架的思路及里面大概的实现过程,那时候忘记上传项目,就补发一下.顺便介绍下框架使用方式,并分析下框架使用的优缺点. 先发一下前两章的链接 篇一:http://www.cnblogs. ...
- html5手势操作与多指操作封装与Canvas图片裁切实战
当前情况,移动端的开发占比越来越高,单指的拖拽触碰等操作是常规需要.特殊的多指操作与手势操作还需另做处理,而且还涉及到兼容性问题. // 屏幕上存在两根或两根以上的手指 时触发 仅IOS存在手势事件, ...
- .Net Excel操作之NPOI(二)常用操作封装
一.Excel数据导出常用操作 1.指定表头和描述 2.指定数据库中读出的数据集合 二.ExcelExport封装 /// <summary> /// Excel常用的表格导出逻辑封装 / ...
- python openpyxl 2.5.4 版本 excel常用操作封装
最近搭框架用的openpyxl 2.5.4版本,之前封装的函数有些提示不推荐使用了,我做了一些更新: 代码: # encoding=utf-8 from openpyxl import load_wo ...
- libxl库的介绍,对Excel操作封装得很好的一个库,兼容2007版和多字节字符(最后有破解版下载)
前段时间忙着毕业论文,终于有时间写博客了. 早些时候老大给我的一个任务需要对excel进行读表操作,研究了一下c++对excel的操作. 对Excel的操作基本有com,ODBC,AD等,其中ODBC ...
- redis操作封装整理
<?php /** * redis操作类 * 说明,任何为false的串,存在redis中都是空串. * 只有在key不存在时,才会返回false. * 这点可用于防止缓存穿透 * */ cla ...
随机推荐
- [Web API] 如何让 Web API 统一回传格式以及例外处理[转]
[Web API] 如何让 Web API 统一回传格式以及例外处理 前言 当我们在开发 Web API 时,一般的情况下每个 API 回传的数据型态或格式都不尽相同,如果你的项目从头到尾都是由你一个 ...
- ThinkPHP中U方法与url的四种访问模式
ThinkPHP中U方法的用处主要是完成对url地址的组装,在模板中使用U方法而不是固定写死URL地址的好处在于,一旦你的环境变化或者参数设置改变,你不需要更改模板中的任何代码.在模板中的调用格式需 ...
- public private protected和默认的区别(转自百度)
public private protected和默认的区别 Java中对类以及类中的成员变量和成员方法通过访问控制符(access specifier)进行区分控制.刚学Java语言的同学可能对pu ...
- Hadoop上路-03_Hadoop JavaAPI
一.Eclipse安装 1.下载解压 下载:http://www.eclipse.org/downloads/ 解压:SHELL$ sudo tar -zxvf eclipse.tar.gz 2.快捷 ...
- 文本分类之特征描述vsm和bow
当我们尝试使用统计机器学习方法解决文本的有关问题时,第一个需要的解决的问题是,如果在计算机中表示出一个文本样本.一种经典而且被广泛运用的文本表示方法,即向量空间模型(VSM),俗称“词袋模型”. 我们 ...
- 第二百三十七天 how can I 坚持
最近好像迷上看小说了,<灵域>,而且也感觉会看小说了. 话说,今天好冷啊,真怕在路上冻着就冻萌了,寒风赤骨啊. 好想买个帽子.好想让送个帽子. 睡觉.
- homework-02 "最大子数组之和"的问题进阶
代码编写 这次的作业瞬间难了好多,无论是问题本身的难度或者是单元测试这一原来没接触过的概念或者是命令行参数的处理这些琐碎的问题,都使得这次作业的完成说不上轻松. 最大子数组之和垂直水平相连的拓展问题解 ...
- HDU 5791 Two (DP)
Two 题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5791 Description Alice gets two sequences A and ...
- Java线程池学习
Java线程池学习 Executor框架简介 在Java 5之后,并发编程引入了一堆新的启动.调度和管理线程的API.Executor框架便是Java 5中引入的,其内部使用了线程池机制,它在java ...
- 经典代码-C宏 #转字符串【瓦特芯 笔记】
在调试C语言程序时,有时需要打印宏的名字.可以通过定义宏,宏名字的数组来获得. 例如: #include <stdio.h> #define MACRO_STR(x) {x, #x} ty ...