Java中创建操作文件和文件夹的工具类
Java中创建操作文件和文件夹的工具类
FileUtils.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel; import org.junit.Test; /**
*
* @version 创建时间:2010-6-8 下午02:58:29
* @Description
*/ public class FileUtils {
/**
* 获取文件编码格式
* @param fileName
* @return
* @throws Exception
*/
public static String getFileEncoding(String fileName) throws Exception {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
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";
} return code;
} /**
* 拷贝文件到指定的路径 (使用了自定义的CopyFileUtil工具类)
* @param fileURL
* @param targetFile
*/
public void copy(String fileURL ,String targetFile){
URLConnection urlconn = null ;
try {
URL url = new URL(fileURL);
urlconn = url.openConnection();
InputStream in = urlconn.getInputStream(); File newfile = new File(targetFile);
FileOutputStream fos = new FileOutputStream(newfile);
CopyFileUtil.copy(in, fos);//使用了自定义的FileUtil工具类
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 复制文件
* @param sourceFile
* @param targetFile
* @throws IOException
*/
public static void copyFile(File sourceFile, File targetFile)
throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
// 关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
} /**
* 复制文件夹
* @param sourceDir
* @param targetDir
* @throws IOException
*/
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目标目录
(new File(targetDir)).mkdirs();
// 获取源文件夹当前下的文件或目录
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile = file[i];
// 目标文件
File targetFile = new File(new File(targetDir)
.getAbsolutePath()
+ File.separator + file[i].getName());
if (sourceFile.getName().indexOf(".vax") < 0)
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
// 准备复制的源文件夹
String dir1 = sourceDir + "/" + file[i].getName();
// 准备复制的目标文件夹
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
} /**
* 得到文件的扩展名
* @param f
* @return
*/
public static String getFileExtension(File f) {
if (f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if (i > 0 && i < filename.length() - 1) {
return filename.substring(i + 1).toLowerCase();
}
}
return null;
}
/**
* 得到文件名(排除文件扩展名)
* @param f
* @return
*/
public static String getFileNameWithoutExt(File f) {
if (f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if (i > 0 && i < filename.length() - 1) {
return filename.substring(0, i);
}
}
return null;
} /**
* 改变文件的扩展名
* @param fileNM
* @param ext
* @return
*/
public static String changeFileExt(String fileNM, String ext) {
int i = fileNM.lastIndexOf('.');
if (i >= 0)
return (fileNM.substring(0, i) + ext);
else
return fileNM;
} /**
* 得到文件的全路径
* @param filePath
* @return
*/
public static String getFileNameWithFullPath(String filePath) {
int i = filePath.lastIndexOf('/');
int j = filePath.lastIndexOf("\\");
int k;
if (i >= j) {
k = i;
} else {
k = j;
}
int n = filePath.lastIndexOf('.');
if (n > 0) {
return filePath.substring(k + 1, n);
} else {
return filePath.substring(k + 1);
}
} /**
* 判断目录是否存在
* @param strDir
* @return
*/
public static boolean existsDirectory(String strDir) {
File file = new File(strDir);
return file.exists() && file.isDirectory();
} /**
* 判断文件是否存在
* @param strDir
* @return
*/
public static boolean existsFile(String strDir) {
File file = new File(strDir);
return file.exists();
} /**
* 强制创建目录
* @param strDir
* @return
*/
public static boolean forceDirectory(String strDir) {
File file = new File(strDir);
file.mkdirs();
return existsDirectory(strDir);
} /**
* 得到文件的大小
* @param fileName
* @return
*/
public static int getFileSize(String fileName){ File file = new File(fileName);
FileInputStream fis = null;
int size = 0 ;
try {
fis = new FileInputStream(file);
size = fis.available();
}catch (Exception e) {
e.printStackTrace();
}
return size ;
} }
CpoyFileUtil.java(主要都是文件复制相关的方法)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.CollationKey;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List; import org.apache.log4j.Logger; /**
* Simple utility methods for file and stream copying.
* All copy methods use a block size of 4096 bytes,
* and close all affected streams when done.
*
* <p>Mainly for use within the framework,
* but also useful for application code.
*
* @author John Summer
*/
public abstract class CopyFileUtil { private static final Logger logger = Logger.getLogger(FileUtil.class); public static final int BUFFER_SIZE = 4096; /**
* judge whether it's exist
* @param strFilePath String
* @return boolean
*/
public static boolean isExist(String filepath) {
File file = new File(filepath);
return file.exists();
} public static void copy(String fileURL ,String targetFile){
URLConnection urlconn = null ;
try {
URL url = new URL(fileURL);
urlconn = url.openConnection();
InputStream in = urlconn.getInputStream(); File newfile = new File(targetFile);
FileOutputStream fos = new FileOutputStream(newfile);
FileUtil.copy(in, fos);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* Copy the contents of the given input File to the given output File.
* @param in the file to copy from
* @param out the file to copy to
* @return the number of bytes copied
* @throws IOException in case of I/O errors
*/
public static int copy(File in, File out) throws IOException {
Assert.notNull(in, "No input File specified");
Assert.notNull(out, "No output File specified");
return copy(new BufferedInputStream(new FileInputStream(in)),
new BufferedOutputStream(new FileOutputStream(out)));
} /**
* Copy the contents of the given byte array to the given output File.
* @param in the byte array to copy from
* @param out the file to copy to
* @throws IOException in case of I/O errors
*/
public static void copy(byte[] in, File out) throws IOException {
Assert.notNull(in, "No input byte array specified");
Assert.notNull(out, "No output File specified");
ByteArrayInputStream inStream = new ByteArrayInputStream(in);
OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out));
copy(inStream, outStream);
} /**
* Copy the contents of the given input File into a new byte array.
* @param in the file to copy from
* @return the new byte array that has been copied to
* @throws IOException in case of I/O errors
*/
public static byte[] copyToByteArray(File in) throws IOException {
Assert.notNull(in, "No input File specified");
return copyToByteArray(new BufferedInputStream(new FileInputStream(in)));
} /**
* Copy the contents of the given InputStream to the given OutputStream.
* Closes both streams when done.
* @param in the stream to copy from
* @param out the stream to copy to
* @return the number of bytes copied
* @throws IOException in case of I/O errors
*/
public static int copy(InputStream in, OutputStream out) throws IOException {
Assert.notNull(in, "No InputStream specified");
Assert.notNull(out, "No OutputStream specified");
try {
int byteCount = 0;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
}
finally {
try {
in.close();
}
catch (IOException ex) {
logger.warn("Could not close InputStream", ex);
}
try {
out.close();
}
catch (IOException ex) {
logger.warn("Could not close OutputStream", ex);
}
}
} /**
* Copy the contents of the given byte array to the given OutputStream.
* Closes the stream when done.
* @param in the byte array to copy from
* @param out the OutputStream to copy to
* @throws IOException in case of I/O errors
*/
public static void copy(byte[] in, OutputStream out) throws IOException {
Assert.notNull(in, "No input byte array specified");
Assert.notNull(out, "No OutputStream specified");
try {
out.write(in);
}
finally {
try {
out.close();
}
catch (IOException ex) {
logger.warn("Could not close OutputStream", ex);
}
}
} /**
* Copy the contents of the given InputStream into a new byte array.
* Closes the stream when done.
* @param in the stream to copy from
* @return the new byte array that has been copied to
* @throws IOException in case of I/O errors
*/
public static byte[] copyToByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
copy(in, out);
return out.toByteArray();
} /**
* Copy the contents of the given Reader to the given Writer.
* Closes both when done.
* @param in the Reader to copy from
* @param out the Writer to copy to
* @return the number of characters copied
* @throws IOException in case of I/O errors
*/
public static int copy(Reader in, Writer out) throws IOException {
Assert.notNull(in, "No Reader specified");
Assert.notNull(out, "No Writer specified");
try {
int byteCount = 0;
char[] buffer = new char[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
}
finally {
try {
in.close();
}
catch (IOException ex) {
logger.warn("Could not close Reader", ex);
}
try {
out.close();
}
catch (IOException ex) {
logger.warn("Could not close Writer", ex);
}
}
} /**
* Copy the contents of the given String to the given output Writer.
* Closes the write when done.
* @param in the String to copy from
* @param out the Writer to copy to
* @throws IOException in case of I/O errors
*/
public static void copy(String in, Writer out) throws IOException {
Assert.notNull(in, "No input String specified");
Assert.notNull(out, "No Writer specified");
try {
out.write(in);
}
finally {
try {
out.close();
}
catch (IOException ex) {
logger.warn("Could not close Writer", ex);
}
}
} /**
* Copy the contents of the given Reader into a String.
* Closes the reader when done.
* @param in the reader to copy from
* @return the String that has been copied to
* @throws IOException in case of I/O errors
*/
public static String copyToString(Reader in) throws IOException {
StringWriter out = new StringWriter();
copy(in, out);
return out.toString();
} }
Java中创建操作文件和文件夹的工具类的更多相关文章
- Java中常用的加密方式(附多个工具类)
一.Java常用加密方式 Base64加密算法(编码方式) MD5加密(消息摘要算法,验证信息完整性) 对称加密算法 非对称加密算法 数字签名算法 数字证书 二.分类按加密算法是否需要key被分为两类 ...
- Java中windows路径转换成linux路径等工具类
项目中发现别人写好的操作系统相关的工具类: 我总结的类似相关博客:http://www.cnblogs.com/DreamDrive/p/4289860.html import java.net.In ...
- java中unicode utf-8以及汉字之间的转换工具类
1. 汉字字符串与unicode之间的转换 1.1 stringToUnicode /** * 获取字符串的unicode编码 * 汉字"木"的Uni ...
- File类的特点?如何创建File类对象?Java中如何操作文件内容,什么是Io流Io流如何读取和写入文件?字节缓冲流使用原则?
重难点提示 学习目标 1.能够了解File类的特点(存在的意义,构造方法,常见方法) 2.能够了解什么是IO流以及分类(IO流的概述以及分类) 3.能够掌握字节输出流的使用(继承体系结构介绍以及常见的 ...
- Java操作文件夹的工具类
Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...
- 总结java中创建并写文件的5种方式
在java中有很多的方法可以创建文件写文件,你是否真的认真的总结过?下面笔者就帮大家总结一下java中创建文件的五种方法. Files.newBufferedWriter(Java 8) Files. ...
- Java中常用IO流之文件流的基本使用姿势
所谓的 IO 即 Input(输入)/Output(输出) ,当软件与外部资源(例如:网络,数据库,磁盘文件)交互的时候,就会用到 IO 操作.而在IO操作中,最常用的一种方式就是流,也被称为IO流. ...
- 使用java 程序创建格式为utf-8文件的方法(写入和读取json文件)
使用java 程序创建格式为utf-8文件的方法: try{ File file=new File("C:/11.jsp"); ...
- Java中使用HttpPost上传文件以及HttpGet进行API请求(包含HttpPost上传文件)
Java中使用HttpPost上传文件以及HttpGet进行API请求(包含HttpPost上传文件) 一.HttpPost上传文件 public static String getSuffix(fi ...
随机推荐
- Fragment进阶
fragment之间的通信,fragment和Activity生命周期之间的关系 通过上一篇浅显的学习了一下,怎么在Activity中添加fragment.在介绍fragment之间的通信之前,我们来 ...
- PaaS平台资源
http://www.vagrantup.com/ http://www.docker.com/
- 当spring 容器初始化完成后执行某个方法 防止onApplicationEvent方法被执行两次
在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查. 比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出 ...
- Notepad++配置Python运行环境
转自:http://www.cnblogs.com/zhcncn/p/3969419.html Notepad++配置Python开发环境 1. 安装Python 1 下载 我选择了32位的2.7 ...
- uva539 The Settlers of Catan
The Settlers of Catan Within Settlers of Catan, the 1995 German game of the year, players attempt to ...
- CodeForces 173C Spiral Maximum 记忆化搜索 滚动数组优化
Spiral Maximum 题目连接: http://codeforces.com/problemset/problem/173/C Description Let's consider a k × ...
- TP常用函数
英文字符可用形如 {$vo.title|substr=0,5} 如果是中文字符thinkphp提供了msubstr如下 function msubstr($str, $start=0, $length ...
- [Angular2 Router] Style the Active Angular 2 Navigation Element with routerLinkActive
You can easily show the user which route they are on using Angular 2’s routerLinkActive. Whenever a ...
- THD 变量存入threads中
http://blog.csdn.net/gapaul/article/details/12047497 http://ourmysql.com/archives/930
- 使用boost的deadline_timer实现一个异步定时器
概述 最近在工作上需要用到定时器,然后看到boost里面的deadline_timer可以实现一个定时器,所以就直接将其封装成了ATimer类,方便使用,ATimer有以下优点: 可以支持纳秒.毫秒. ...