package com.bood.common.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
/**
* 文件操作工具類 拷貝|刪除|寫入|讀取
*
* @author:bood
* @since:2020/2/7
*/
@SuppressWarnings("deprecation")
public class FileUtils {
public FileUtils() {
}
/**
* 拷貝文件
*
* @param src 源文件
* @param dest 目標文件
* @param bufferSize 每次讀取的字節數
* @throws IOException
*/
public static void copyFile(String src, String dest, int bufferSize)
throws IOException {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest);
byte[] buffer = new byte[bufferSize];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
}
/**
* 刪除文件
*
* @param src 源文件
*/
public static void deleteFile(String src) {
new File(src).delete();
}
/**
* 刪除多個文件
*
* @param src 源文件數組
*/
public static void deleteFiles(String... src) {
for (String s : src) {
FileUtils.deleteFile(s);
}
}
/**
* 根據路徑刪除文件,不能刪除子目錄下的文件
*
* @param dir 目錄
* @throws Exception
*/
@Deprecated
public static void deleteByDir(String dir) throws Exception {
File d = new File(dir);
if (!d.isDirectory()) return;
String[] fileNameArray = d.list();
FileUtils.deleteFiles(fileNameArray);
}
/**
* 遞歸刪除目錄下的所有文件及子目錄下所有文件
*
* @param dir 將要刪除的文件目錄
*/
public static boolean deleteByDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
//遞歸刪除目錄中的子目錄下
for (int i = 0; i < children.length; i++) {
boolean success = deleteByDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目錄此時爲空,可以刪除
return dir.delete();
}
/**
* 遞歸刪除目錄下的所有文件及子目錄下指定類型的所有文件
*
* @param dir
* @param fileSuffix 文件名後綴,如:jpg,doc,不含“.”,<font color=red>區分JPG和jpg的大小寫</font>
* @return
*/
public static boolean deleteByFileTypes(File dir, boolean deleteEmptyDir, String... fileSuffix) {
if (dir.isFile()) return false;
if (dir.isDirectory()) {
File[] children = dir.listFiles();
//遞歸刪除目錄中的子目錄下
for (int i = 0; i < children.length; i++) {
//如果是目錄
if (children[i].isDirectory()) {
if (!deleteByFileTypes(children[i], deleteEmptyDir, fileSuffix)) {
return false;
}
}
//匹配文件後綴
if (matchFileType(children[i], fileSuffix)) {
if (!children[i].delete()) {
return false;
}
}
}
}
//刪除空文件夾
if (deleteEmptyDir) {
if (dir.list().length == 0) {
if (!dir.delete()) {
return false;
}
}
}
return true;
}
/**
* '匹配文件的後綴
*
* @param file
* @param fileSuffix
* @return
*/
private static boolean matchFileType(File file, String... fileSuffix) {
String fileName = file.getName();
for (String suffix : fileSuffix) {
if (fileName.endsWith("." + suffix)) {
return true;
}
}
return false;
}
/**
* 將內容寫入文件<font color=red>寫文件不要用FileWriter,因爲這個無法設置編碼,使用系統的編碼格式</font>
*
* @param content 寫入的內容
* @param dest 寫入的文件
* @param append 是否追加
* @param newLine 是否換行
* @throws IOException
*/
public static void writeToFile(String content, String dest, boolean append,
boolean newLine) throws IOException {
writeToFile(content, dest, append, newLine, Charset.forName("UTF-8"));
}
/**
* 將內容寫入文件
*
* @param content 寫入的內容
* @param dest 寫入的文件
* @param append 是否追加
* @param newLine 是否換行
* @param charset 字符編碼
* @throws IOException
*/
public static void writeToFile(String content, String dest, boolean append,
boolean newLine, Charset charset) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(dest, true), charset);
writer.write(content + (newLine == true ? System.getProperty("line.separator") : ""));
writer.close();
}
/**
* 獲取文件內容
*
* @param src 源文件
* @return String[] 文件內容數組,每行佔一個數組空間
* @throws IOException
*/
public static String[] readContent(String src, Charset charset)
throws IOException {
FileReader reader = new FileReader(src);
BufferedReader br = new BufferedReader(reader);
String[] array = new String[FileUtils.readLineNumber(src)];
String line;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
array[lineNumber] = line;
lineNumber++;
}
reader.close();
br.close();
return array;
}
/**
* 獲取文件內容
*
* @param src 源文件
* @return String[] 文件內容數組,每行佔一個數組空間
* @throws IOException
*/
public static String readStringContent(String src) throws IOException {
FileReader reader = new FileReader(src);
BufferedReader br = new BufferedReader(reader);
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
reader.close();
br.close();
return sb.toString();
}
/**
* 獲取文件行數
*
* @param src 源文件
* @return int 內容行數
* @throws IOException
*/
public static int readLineNumber(String src) throws IOException {
FileReader reader = new FileReader(src);
BufferedReader br = new BufferedReader(reader);
int lineNumber = 0;
while (br.readLine() != null) {
lineNumber++;
}
reader.close();
br.close();
return lineNumber;
}
/**
* 獲取目錄下的文件和文件夾列表
*
* @param dir 源目錄
* @return LinkedHashMap<String, Boolean> true表示目錄
* @throws Exception
*/
public static LinkedHashMap<String, Boolean> readDir(String dir)
throws Exception {
File d = new File(dir);
if (!d.isDirectory())
throw new Exception("\"" + dir + "\"" + "不是一個目錄");
String[] array = d.list();
if (array == null)
return null;
LinkedHashMap<String, Boolean> map = new LinkedHashMap<String, Boolean>();
for (int i = 0; i < array.length; i++) {
map.put(array[i], new File(dir + File.separatorChar + array[i])
.isDirectory() == true ? true : false);
}
return map;
}
/**
* 移動文件,不可以移動文件家
*
* @param src 源文件
* @param dest 目標文件
*/
public static void moveFile(String src, String dest) {
new File(src).renameTo(new File(dest));
}
/**
* 重命名文件||實際上調用本類的moveFile方法
*
* @param src 源文件
* @param dest 目標文件
*/
public static void renameFile(String src, String dest) {
moveFile(src, dest);
}
/**
* 從URL抓取一個文件寫到本地<br>,有可能會出現403的情況
* 這個方法摘自 <a href="http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html">org.apache.commons.io.FileUtils.copyURLToFile(URL source, File destination)</a>
*
* @param source
* @param destination
* @throws IOException
*/
public static void copyFileFromURL(URL source, File destination) throws IOException {
InputStream input = null;
FileOutputStream output = null;
byte[] buffer = new byte[1024];
input = source.openStream();
if (destination.exists()) {
if (destination.isDirectory()) {
throw new IOException("File '" + destination
+ "' exists but is a directory");
}
if (destination.canWrite() == false) {
throw new IOException("File '" + destination
+ "' cannot be written to");
}
} else {
File parent = destination.getParentFile();
if (parent != null) {
if (!parent.mkdirs() && !parent.isDirectory()) {
throw new IOException("Directory '" + parent
+ "' could not be created");
}
}
}
output = new FileOutputStream(destination, true);
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
output.close();
input.close();
}
/**
* 複製一個目錄及其子目錄、文件到另外一個目錄
*
* @param src
* @param dest
* @throws IOException
*/
public static void copyDir(String _src, String _target) throws IOException {
File src = new File(_src);
File dest = new File(_target);
if (src.isDirectory()) {
if (!dest.exists()) {
dest.mkdirs();
}
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dest, file);
// 遞歸複製
copyDir(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
}
} else {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
/**
* 目錄重命名
*
* @param sourceDirName
* @param targetDirName
*/
public static void renameDirectory(String sourceDirName, String targetDirName) {
new File(sourceDirName).renameTo(new File(targetDirName));
}
/**
* 獲取目錄下所有文件
*
* @param realpath
* @param files
* @param listSubDir 是否包含子目錄
* @return
*/
public static List<File> getFiles(String realpath, List<File> files, boolean listSubDir) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] _files = realFile.listFiles();
if (!listSubDir) return Arrays.asList(_files);
for (File file : _files) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files, true);
} else {
files.add(file);
}
}
}
return files;
}
/**
* 獲取目錄下所有文件(包括子文件夾)
* 遞歸調用
*
* @param realpath
* @param files
* @return
*/
public static List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles();
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
}
}
return files;
}
/**
* 獲取目錄下所有文件(按修改時間排序)
*
* @param path
* @return
*/
public static List<File> getFileSort(String path) {
List<File> list = getFiles(path, new ArrayList<File>());
if (list != null && list.size() > 0) {
Collections.sort(list, new Comparator<File>() {
public int compare(File file, File newFile) {
if (file.lastModified() < newFile.lastModified()) {
return 1;
} else if (file.lastModified() == newFile.lastModified()) {
return 0;
} else {
return -1;
}
}
});
}
return list;
}
/**
* 從網絡下載文件,不會出現403的情況
*
* @param url
* @param filePathName
*/
public static void download(String url, String filePathName) {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet(url);
// 僞裝成google的爬蟲,一般服務器會進行請求的校驗,如果不是http請求會進行攔截
httpget.setHeader("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
HttpResponse response = httpclient.execute(httpget);
File storeFile = new File(filePathName);
FileOutputStream output = new FileOutputStream(storeFile);
// 得到網絡資源的字節數組,並寫入文件
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
byte b[] = new byte[1024];
int j = 0;
while ((j = instream.read(b)) != -1) {
output.write(b, 0, j);
}
output.flush();
output.close();
} catch (IOException ex) {
throw ex;
} catch (RuntimeException ex) {
httpget.abort();
throw ex;
} finally {
try {
instream.close();
httpget.releaseConnection();
} catch (Exception ignore) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
/**
* 獲取文件後綴名
*
* @param file
* @return
*/
public static String getFileSuffix(File file) {
if (!file.isFile() || !file.exists())
return null;
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos == -1) {
return null;
}
return name.substring(pos + 1, name.length());
}
}
Java.Utils:文件操作工具類 拷貝|刪除|寫入|讀取
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.