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 ...
随机推荐
- 结构类模式(六):享元(Flyweight)
定义 运用共享技术有效的支持大量细粒度的对象. 两个状态 内蕴状态存储在享元内部,不会随环境的改变而有所不同,是可以共享的. 外蕴状态是不可以共享的,它随环境的改变而改变的,因此外蕴状态是由客户端来保 ...
- Oracle Job相关
Oracle JOB的建立,定时执行任务 begin sys.dbms_job.submit(job => :job, ...
- GetSafeHwnd()函数解释[转]
当我们想得到一个窗口对象(CWnd的派生对象)指针的句柄(HWND)时,最安全的方法是使用GetSafeHwnd()函数,通过下面的例子来看其理由: CWnd *pwnd = FindWindow(“ ...
- map 转换 xml ; xml转map
public class MessageKit { public static String map2xml(Map<String, String> map) throws IOExcep ...
- MFC中修改静态文本框中文字的字体、颜色
假设有一个静态文本框控件,其ID为:IDC_STATIC_XSDJ,且关联一个control类的CStatic类型的变量m_static_xsdj. 设置字体时自然要用到CFont类,下面介绍两种方法 ...
- 如何自学Java
转自:http://www.360doc.com/content/12/0624/19/5856897_220191533.shtml JAVA自学之路 JAVA自学之路 一:学会选择 为了就业, ...
- MiinCMP1.0 SAE 新浪云版公布, 开源企业站点系统
MiinCMP是一款开源企业站点系统,除可执行于256M左右100元的国内IDC外,JUULUU聚龙软件团队最近开发了面向新浪云的版本号,该版本号可将站点免费布署到新浪云SAE上.MiinCMP採用j ...
- cdoj 80 Cube 水题
Cube Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/problem/show/80 Descrip ...
- Codeforces Round #189 (Div. 1) B. Psychos in a Line 单调队列
B. Psychos in a Line Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/problemset/p ...
- iOS CocoaPods安装和使用图解
Cocoapods安装步骤 1.升级Ruby环境 sudo gem update --system 如果Ruby没有安装,请参考 如何在Mac OS X上安装 Ruby运行环境 2.安装CocoaPo ...