文件操作

package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.StringTokenizer;

public class FileUtil {

/**
* 读取文本文件内容
*
* @param filePathAndName
* 带有完整绝对路径的文件名
* @param encoding
* 文本文件打开的编码方式
* @return 返回文本文件的内容
*/
public static String readTxt(String filePathAndName, String encoding)
throws IOException {
encoding = encoding.trim();
StringBuffer str = new StringBuffer("");
String st = "";
try {
FileInputStream fs = new FileInputStream(filePathAndName);
InputStreamReader isr;
if (encoding.equals("")) {
isr = new InputStreamReader(fs);
} else {
isr = new InputStreamReader(fs, encoding);
}
BufferedReader br = new BufferedReader(isr);
try {
String data = "";
while ((data = br.readLine()) != null) {
str.append(data + "\r\n");
}
} catch (IOException e) {
str.append(e.toString());
}
st = str.toString();
} catch (IOException es) {
throw es;
}
return st;
}

/**
* 新建文件
*
* @param filePathAndName
* 文本文件完整绝对路径及文件名
* @param fileContent
* 文本文件内容
* @return
* @throws Exception
*/
public static void createFile(String filePathAndName, String fileContent)
throws Exception {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
resultFile.close();
} catch (Exception e) {
throw new Exception("创建文件操作出错", e);
}
}

/**
* 有编码方式的文件创建
*
* @param filePathAndName
* 文本文件完整绝对路径及文件名
* @param fileContent
* 文本文件内容
* @param encoding
* 编码方式 例如 GBK 或者 UTF-8
* @return
* @throws Exception
*/
public static void createFile(String filePathAndName, String fileContent,
String encoding) throws Exception {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
PrintWriter myFile = new PrintWriter(myFilePath, encoding);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
} catch (Exception e) {
throw new Exception("创建文件操作出错", e);
}
}

/**
* 创建文件夹
*
* @param filePath
* @throws Exception
*/
public static String createFolder(String filePath) throws Exception {
File file = new java.io.File(filePath);
try {
if (!file.exists()) {
if (!file.mkdir()) {
throw new IOException("创建文件夹:" + filePath + "出错");
}
}
return filePath;
} catch (Exception e) {
throw e;
}
}

/**
* 多级目录创建
*
* @param folderPath
* 准备要在本级目录下创建新目录的目录路径 例如 E:\\Test\\java\\
* @param paths
* 无限级目录参数,各级目录以单数线区分 例如 a|b|c
* @return 返回创建文件夹后的路径 例如 c:myfa c
* @throws Exception
*/
public static String createFolders(String folderPath, String paths)
throws Exception {
String txts = folderPath;
try {
String txt;
txts = folderPath;
StringTokenizer st = new StringTokenizer(paths, "|");
for (int i = 0; st.hasMoreTokens(); i++) {
txt = st.nextToken().trim();
txts = createFolder(txts + txt + "/");
}
} catch (Exception e) {
throw new Exception("创建目录操作出错!", e);
}
return txts;
}

/**
* 复制单个文件
*
* @param oldPathFile
* 准备复制的文件源
* @param newPathFile
* 拷贝到新绝对路径带文件名
* @return
* @throws Exception
*/
public static void copyFile(String oldPathFile, String newPathFile)
throws Exception {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPathFile);
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
FileOutputStream fs = new FileOutputStream(newPathFile);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
throw e;
}
}

/**
* <p>
* 将sourceFolder文件夹下的内容复制到destinationFolder文件夹下
* </p>
* <p>
* 如destinationFolder文件夹不存在则自动创建
* </p>
*
* @param sourceFolder
* 源文件夹 如:C:\\aaa
* @param destinationFolder
* 目标文件夹 D:\\java
* @throws Exception
*/
public static void copyFolder(String sourceFolder, String destinationFolder)
throws Exception {
try {
new File(destinationFolder).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(sourceFolder);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (sourceFolder.endsWith(File.separator)) {
temp = new File(sourceFolder + file[i]);
} else {
temp = new File(sourceFolder + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
destinationFolder + "/"
+ (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(sourceFolder + "/" + file[i], destinationFolder
+ "/" + file[i]);
}
}
} catch (Exception e) {
throw new Exception("复制整个文件夹内容操作出错", e);
}
}

/**
* 删除文件
*
* @param filePathAndName
* 文本文件完整绝对路径及文件名
* @return Boolean 成功删除返回true遭遇异常返回false
*/
public static void delFile(String filePathAndName) throws Exception {
try {
String filePath = filePathAndName;
File myDelFile = new File(filePath);
if (myDelFile.exists()) {
myDelFile.delete();
} else {
throw new IOException(filePathAndName + "删除文件操作出错");
}
} catch (IOException e) {
throw new Exception(filePathAndName + "删除文件操作出错", e);
}
}

/**
* 删除文件夹
*
* @param folderPath
* 文件夹完整绝对路径
* @return
* @throws Exception
*/
public static void delFolder(String folderPath) throws Exception {

try {
delAllFile(folderPath);
// 删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
boolean result = myFilePath.delete(); // 删除空文件夹
if (!result) {
throw new IOException("文件夹:" + folderPath + ",删除失败");
}
} catch (IOException e) {
throw new Exception("删除文件夹出错", e);
}
}

/**
* 删除文件及文件夹下所有文件
*
* @return
* @throws IOException
*/
public static boolean delAllFile(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists())// 文件夹不存在不存在
throw new IOException("指定目录不存在:" + file.getName());
boolean rslt = true;// 保存中间结果
if (!(rslt = file.delete())) {// 先尝试直接删除
// 若文件夹非空。枚举、递归删除里面内容
File subs[] = file.listFiles();
for (int i = 0; i <= subs.length - 1; i++) {
if (subs[i].isDirectory())
delAllFile(subs[i].toString());// 递归删除子文件夹内容
rslt = subs[i].delete();// 删除子文件夹本身
}
// rslt = file.delete();// 删除此文件夹本身
}

if (!rslt)
throw new IOException("无法删除:" + file.getName());
// 删除文件
return true;
}

/**
* 移动文件
*
* @param oldPath
* @param newPath
* @return
* @throws Exception
*/
public static void moveFile(String oldPath, String newPath)
throws Exception {

try {
copyFile(oldPath, newPath);
delFile(oldPath);
} catch (Exception e) {
throw e;
}

}

/**
* 移动目录
*
* @param oldPath
* @param newPath
* @return
*/
public static void moveFolder(String oldPath, String newPath) {
try {
copyFolder(oldPath, newPath);
delFolder(oldPath);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* <p>
* 取得当前类文件所在绝对路径
* </p>
* <p>
* 如:E:/workspace/mobile/WebRoot/WEB-INF/classes/com/mobileSky/ty/utils/
* </p>
*
* @return
*/
public static String getClassPath() {
String strClassName = FileUtil.class.getName();

String strPackageName = "";
if (FileUtil.class.getPackage() != null) {
strPackageName = FileUtil.class.getPackage().getName();
}

String strClassFileName = "";
if (!"".equals(strPackageName)) {
strClassFileName = strClassName.substring(
strPackageName.length() + 1, strClassName.length());
} else {
strClassFileName = strClassName;
}

URL url = null;
url = FileUtil.class.getResource(strClassFileName + ".class");
String strURL = url.toString();
strURL = strURL.substring(strURL.indexOf('/') + 1, strURL
.lastIndexOf('/'));
return strURL + "/";
}

/**
* 取得当前项目根目录,如:E:/workspace/mobile/,其中mobile为项目名
*
* @param projectName
* @return
*/
public static String getProject(String projectName) {
String classPath = getClassPath();
return classPath.substring(0, classPath.indexOf(projectName)
+ projectName.length() + 1);
}

/**
* 将C:\aaa\dsa转换为C:/aaa/dsa
*
* @param path
* @return
*/
public static String getStr(String path) {
String result = "";
char[] pathChar = path.toCharArray();
for (int i = 0; i < pathChar.length; i++) {
if (pathChar[i] == '\\') {
pathChar[i] = '/';
}
result += pathChar[i];
}
return result;
}

public static void main(String arg[]) {

try {
copyFolder("E:\\百度网页\\百度指数搜索_java.files", "E:\\百度网页\\重新生产\\百度指数搜索_java.files");
//moveFolder("E:\\百度网页\\百度指数搜索_java.files","E:\\百度网页\\xxx\\百度指数搜索_java.files");
// delAllFile("E:\\Test\\java");
// delFolder("E:\\Test\\java");
// createFile("E:\\Test\\java\\a.xml",
// "<abc>\r\n<a>\r\n</a>\r\n</abc>");
// createFolder("E:\\Test\\java");
// createFolders("E:\\Test\\java\\", "一级|二级|三级");
//String a = readTxt("E:\\Test\\java\\a.xml", "GBK");
//System.out.println(a);
} catch (Exception e) {
e.printStackTrace();
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值