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 ...
随机推荐
- VC++ 中滑动条(slider控件)使用 [转+补充]
滑动控件slider是Windows中最常用的控件之一.一般而言它是由一个滑动条,一个滑块和可选的刻度组成,用户可以通过移动滑块在相应的控件中显示对应的值.通常,在滑动控件附近一定有标签控件或编辑框控 ...
- 使用.NET中的Action及Func泛型委托
委托,在C#编程中占有极其重要的地位,委托可以将函数封装到委托对象中,并且多个委托可以合并为一个委托,委托对象则可以像普通对象一样被存储.传递,之后在任何时刻进行调用,因此,C#中函数回调 ...
- (C++)STL排序函数sort和qsort的用法与区别
主要内容: 1.qsort的用法 2.sort的用法 3.qsort和sort的区别 qsort的用法: 原 型: void qsort(void *base, int nelem, int widt ...
- 分享一个导出Excel时页面不跳转的小技巧
今天在点击客户档案导出的时候,发现先是打开了一个新标签,然后新标签自动关掉,弹出一个文件下载确认的窗口,点击确认后开始下载导出的Excel文件.这样的过程感觉窗口闪来闪去,而且可能会给用户带来困惑,是 ...
- IAR EWARM Argument variables $PROJ_DIR$ $TOOLKIT_DIR$
在IAR中的help中输入argument variables时会找到这样的一个列表: Argument variables On many of the pages in the Options d ...
- 永久改动redhat的default route
1,能够用route命令暂时改动: route add default gw <gateway ip> 2, 通过改动/etc/sysconfig/network 文件永久改动: 脚本: ...
- [转]Swift Cheat Sheet
原文:http://kpbp.github.io/swiftcheatsheet/ A quick cheat sheet and reference guide for Apple's Swift ...
- jquery.validate使用攻略
主要分几部分 jquery.validate 基本用法 jquery.validate API说明 jquery.validate 自定义 jquery.validate 常见类型的验证代码 下载地址 ...
- SAP MRP的计算步骤
SAP MRP的计算步骤,物料需求计划(简称为MRP)与主生产计划一样属于ERP计划管理体系,它主要解决企业生产中的物料需求与供给之间的关系,即无论是对独立需求的物料,还是相关需求的物料, ...
- Codeforces Round #308 (Div. 2) D. Vanya and Triangles 水题
D. Vanya and Triangles Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/55 ...