package com.marshalchen.common.commonUtils.fileUtils;
import android.content.Context;
import android.os.Environment;
import com.marshalchen.common.commonUtils.basicUtils.BasicUtils;
import com.marshalchen.common.commonUtils.basicUtils.StringUtils;
import com.marshalchen.common.commonUtils.logUtils.Logs;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* TO do something with File,like read ,del etc.
* User: cym
* Date: 13-10-23
* Time: 上午11:01
*/
public class FileUtils {
public static String readFilesToString(String fileName) throws IOException {
File file = new File(fileName);
if (!file.exists() || file.isDirectory())
throw new FileNotFoundException();
BufferedReader br = new BufferedReader(new FileReader(file));
String temp = null;
StringBuffer sb = new StringBuffer();
temp = br.readLine();
while (temp != null) {
sb.append(temp + "\n");
temp = br.readLine();
}
return sb.toString();
}
public static String getCurrentDataPath(Context context) throws IOException {
return getCurrentDataPath(context, "");
}
public static String getCurrentDataPath(Context context, String folderName) throws IOException {
String currentDataPath = "";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
currentDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + folderName;
createDir(currentDataPath);
} else {
currentDataPath = context.getFilesDir().getAbsolutePath();
}
return currentDataPath;
}
/**
* @param fileName
* @param content
* @throws IOException
* @deprecated
*/
public static void writeFileFromString(String fileName, String content) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(content.getBytes());
bufferedOutputStream.flush();
bufferedOutputStream.close();
fileOutputStream.close();
}
/**
* @param fileName
* @param content
* @throws IOException
* @deprecated
*/
public static void writeFileFromStringBuffers(String fileName, String content) throws IOException {
String s = new String();
String s1 = new String();
try {
File f = new File(fileName);
if (f.exists()) {
Logs.d("文件存在");
} else {
Logs.d("文件不存在,正在创建...");
if (f.createNewFile()) {
Logs.d("文件创建成功!");
} else {
Logs.d("文件创建失败!");
}
}
BufferedReader input = new BufferedReader(new FileReader(f));
while ((s = input.readLine()) != null) {
s1 += s + "\n";
}
System.out.println("文件内容:" + s1);
input.close();
s1 += content;
BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(s1);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create Folder
*
* @param fileName folder
*/
public static void createDir(String fileName) throws IOException {
File dir = new File(fileName);
Logs.d(fileName + " " + dir.exists());
if (!dir.exists())
dir.mkdir();
}/** */
/**
* Create New File
*
* @param path Folder Name
* @param fileName File Name
* @throws java.io.IOException
*/
public static void createFile(String path, String fileName) throws IOException {
File file = new File(path + "/" + fileName);
if (!file.exists())
file.createNewFile();
}/** */
/**
* Delete File
*
* @param fileName
*/
public void delFile(String fileName) throws IOException {
File file = new File(fileName);
if (file.exists() && file.isFile())
file.delete();
}
/**
* Delete the File no matter it's a file or folder.If the file is a folder,this method
* will delete all the file in the folder.
*
* @param fileName
* @throws IOException
*/
public static void deleteFileOrFolder(String fileName) throws IOException {
File f = new File(fileName);
if (f.isDirectory()) {
String[] list = f.list();
for (int i = 0; i < list.length; i++) {
deleteFileOrFolder(fileName + "//" + list[i]);
}
}
f.delete();
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete();
} catch (Exception e) {
Logs.e(e, "");
}
}
/**
* @param path String folder path like c:/fqf
*/
public static void delAllFile(String path) throws IOException {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);
delFolder(path + "/" + tempList[i]);
}
}
}
/**
* append file using FileOutputStream
*
* @param fileName
* @param content
*/
public static void WriteStreamAppendByFileOutputStream(String fileName, String content) throws IOException {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName, true)));
out.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* append file using FileWriter
*
* @param fileName
* @param content
*/
public static void writeStreamAppendByFileWriter(String fileName, String content) throws IOException {
try {
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* append file using RandomAccessFile
*
* @param fileName
* @param content
*/
public static void WriteStreamAppendByRandomAccessFile(String fileName, String content) throws IOException {
try {
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
long fileLength = randomFile.length();
// Write point to the end of file.
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* copy file
*
* @param oldPath String
* @param newPath String
* @return boolean
*/
public static void copyFileFromPath(String oldPath, String newPath) throws IOException {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(oldPath);
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1024];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
System.out.println("copy failed");
e.printStackTrace();
}
}
/**
* Copy File from InputStream
*
* @param is InputStream
* @param newPath String
* @return boolean
*/
public static void copyFileFromInputStream(InputStream is, String newPath) throws IOException {
FileOutputStream fs = null;
try {
int bytesum = 0;
int byteread = 0;
if (is != null) {
fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1024];
int length;
while ((byteread = is.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
is.close();
}
} catch (Exception e) {
System.out.println("Copy Failed");
e.printStackTrace();
} finally {
try {
is.close();
fs.close();
} catch (IOException e) {
e.printStackTrace();
Logs.e(e, "");
}
}
}
/**
* @param oldPath String
* @param newPath String
* @return boolean
* @deprecated Copy all the files in folder
*/
public void copyFolder(String oldPath, String newPath) throws IOException {
try {
(new File(newPath)).mkdirs();
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" +
(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(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
/**
* @param oldPath String 如:c:/fqf.txt
* @param newPath String 如:d:/fqf.txt
*/
public void moveFile(String oldPath, String newPath) throws IOException {
copyFile(oldPath, newPath);
delFile(oldPath);
}
/**
* @param oldPath String
* @param newPath String
*/
public void moveFolder(String oldPath, String newPath) throws IOException {
copyFolder(oldPath, newPath);
delFolder(oldPath);
}
public final static String FILE_EXTENSION_SEPARATOR = ".";
/**
* read file
*
* @param filePath
* @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
* @return if file not exist, return null, else return content of file
* @throws RuntimeException if an error occurs while operator BufferedReader
*/
public static StringBuilder readFile(String filePath, String charsetName) {
File file = new File(filePath);
StringBuilder fileContent = new StringBuilder("");
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals("")) {
fileContent.append("\r\n");
}
fileContent.append(line);
}
reader.close();
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* write file
*
* @param filePath
* @param content
* @param append is append, if true, write to the end of file, else clear content of file and write into it
* @return return false if content is empty, true otherwise
* @throws RuntimeException if an error occurs while operator FileWriter
*/
public static boolean writeFile(String filePath, String content, boolean append) {
if (BasicUtils.judgeNotNull(content)) {
return false;
}
FileWriter fileWriter = null;
try {
makeDirs(filePath);
fileWriter = new FileWriter(filePath, append);
fileWriter.write(content);
fileWriter.close();
return true;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* write file
*
* @param filePath
* @param contentList
* @param append is append, if true, write to the end of file, else clear content of file and write into it
* @return return false if contentList is empty, true otherwise
* @throws RuntimeException if an error occurs while operator FileWriter
*/
public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
if (BasicUtils.judgeNotNull(contentList)) {
return false;
}
FileWriter fileWriter = null;
try {
makeDirs(filePath);
fileWriter = new FileWriter(filePath, append);
int i = 0;
for (String line : contentList) {
if (i++ > 0) {
fileWriter.write("\r\n");
}
fileWriter.write(line);
}
fileWriter.close();
return true;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* write file, the string will be written to the begin of the file
*
* @param filePath
* @param content
* @return
*/
public static boolean writeFile(String filePath, String content) {
return writeFile(filePath, content, false);
}
/**
* write file, the string list will be written to the begin of the file
*
* @param filePath
* @param contentList
* @return
*/
public static boolean writeFile(String filePath, List<String> contentList) {
return writeFile(filePath, contentList, false);
}
/**
* write file, the bytes will be written to the begin of the file
*
* @param filePath
* @param stream
* @return
* @see {@link #writeFile(String, InputStream, boolean)}
*/
public static boolean writeFile(String filePath, InputStream stream) {
return writeFile(filePath, stream, false);
}
/**
* write file
*
* @param filePath the file to be opened for writing.
* @param stream the input stream
* @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
* @return return true
* @throws RuntimeException if an error occurs while operator FileOutputStream
*/
public static boolean writeFile(String filePath, InputStream stream, boolean append) {
return writeFile(filePath != null ? new File(filePath) : null, stream, append);
}
/**
* write file, the bytes will be written to the begin of the file
*
* @param file
* @param stream
* @return
* @see {@link #writeFile(File, InputStream, boolean)}
*/
public static boolean writeFile(File file, InputStream stream) {
return writeFile(file, stream, false);
}
/**
* write file
*
* @param file the file to be opened for writing.
* @param stream the input stream
* @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
* @return return true
* @throws RuntimeException if an error occurs while operator FileOutputStream
*/
public static boolean writeFile(File file, InputStream stream, boolean append) {
OutputStream o = null;
try {
makeDirs(file.getAbsolutePath());
o = new FileOutputStream(file, append);
byte data[] = new byte[1024];
int length = -1;
while ((length = stream.read(data)) != -1) {
o.write(data, 0, length);
}
o.flush();
return true;
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (o != null) {
try {
o.close();
stream.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* copy file
*
* @param sourceFilePath
* @param destFilePath
* @return
* @throws RuntimeException if an error occurs while operator FileOutputStream
*/
public static boolean copyFile(String sourceFilePath, String destFilePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(sourceFilePath);
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
}
return writeFile(destFilePath, inputStream);
}
/**
* read file to string list, a element of list is a line
*
* @param filePath
* @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
* @return if file not exist, return null, else return content of file
* @throws RuntimeException if an error occurs while operator BufferedReader
*/
public static List<String> readFileToList(String filePath, String charsetName) {
File file = new File(filePath);
List<String> fileContent = new ArrayList<String>();
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
fileContent.add(line);
}
reader.close();
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
}
}
}
}
/**
* get file name from path, not include suffix
* <p/>
* <pre>
* getFileNameWithoutExtension(null) = null
* getFileNameWithoutExtension("") = ""
* getFileNameWithoutExtension(" ") = " "
* getFileNameWithoutExtension("abc") = "abc"
* getFileNameWithoutExtension("a.mp3") = "a"
* getFileNameWithoutExtension("a.b.rmvb") = "a.b"
* getFileNameWithoutExtension("c:\\") = ""
* getFileNameWithoutExtension("c:\\a") = "a"
* getFileNameWithoutExtension("c:\\a.b") = "a"
* getFileNameWithoutExtension("c:a.txt\\a") = "a"
* getFileNameWithoutExtension("/home/admin") = "admin"
* getFileNameWithoutExtension("/home/admin/a.txt/b.mp3") = "b"
* </pre>
*
* @param filePath
* @return file name from path, not include suffix
* @see
*/
public static String getFileNameWithoutExtension(String filePath) {
if (isFileExist(filePath)) {
return filePath;
}
int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
int filePosi = filePath.lastIndexOf(File.separator);
if (filePosi == -1) {
return (extenPosi == -1 ? filePath : filePath.substring(0, extenPosi));
}
if (extenPosi == -1) {
return filePath.substring(filePosi + 1);
}
return (filePosi < extenPosi ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1));
}
/**
* get file name from path, include suffix
* <p/>
* <pre>
* getFileName(null) = null
* getFileName("") = ""
* getFileName(" ") = " "
* getFileName("a.mp3") = "a.mp3"
* getFileName("a.b.rmvb") = "a.b.rmvb"
* getFileName("abc") = "abc"
* getFileName("c:\\") = ""
* getFileName("c:\\a") = "a"
* getFileName("c:\\a.b") = "a.b"
* getFileName("c:a.txt\\a") = "a"
* getFileName("/home/admin") = "admin"
* getFileName("/home/admin/a.txt/b.mp3") = "b.mp3"
* </pre>
*
* @param filePath
* @return file name from path, include suffix
*/
public static String getFileName(String filePath) {
if (isFileExist(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
}
/**
* get folder name from path
* <p/>
* <pre>
* getFolderName(null) = null
* getFolderName("") = ""
* getFolderName(" ") = ""
* getFolderName("a.mp3") = ""
* getFolderName("a.b.rmvb") = ""
* getFolderName("abc") = ""
* getFolderName("c:\\") = "c:"
* getFolderName("c:\\a") = "c:"
* getFolderName("c:\\a.b") = "c:"
* getFolderName("c:a.txt\\a") = "c:a.txt"
* getFolderName("c:a\\b\\c\\d.txt") = "c:a\\b\\c"
* getFolderName("/home/admin") = "/home"
* getFolderName("/home/admin/a.txt/b.mp3") = "/home/admin/a.txt"
* </pre>
*
* @param filePath
* @return
*/
public static String getFolderName(String filePath) {
if (isFileExist(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
}
/**
* get suffix of file from path
* <p/>
* <pre>
* getFileExtension(null) = ""
* getFileExtension("") = ""
* getFileExtension(" ") = " "
* getFileExtension("a.mp3") = "mp3"
* getFileExtension("a.b.rmvb") = "rmvb"
* getFileExtension("abc") = ""
* getFileExtension("c:\\") = ""
* getFileExtension("c:\\a") = ""
* getFileExtension("c:\\a.b") = "b"
* getFileExtension("c:a.txt\\a") = ""
* getFileExtension("/home/admin") = ""
* getFileExtension("/home/admin/a.txt/b") = ""
* getFileExtension("/home/admin/a.txt/b.mp3") = "mp3"
* </pre>
*
* @param filePath
* @return
*/
public static String getFileExtension(String filePath) {
if (StringUtils.isBlank(filePath)) {
return filePath;
}
int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
int filePosi = filePath.lastIndexOf(File.separator);
if (extenPosi == -1) {
return "";
}
return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
}
/**
* Creates the directory named by the trailing filename of this file, including the complete directory path required
* to create this directory. <br/>
* <br/>
* <ul>
* <strong>Attentions:</strong>
* <li>makeDirs("C:\\Users\\Trinea") can only create users folder</li>
* <li>makeFolder("C:\\Users\\Trinea\\") can create Trinea folder</li>
* </ul>
*
* @param filePath
* @return true if the necessary directories have been created or the target directory already exists, false one of
* the directories can not be created.
* <ul>
* <li>if {@link FileUtils#getFolderName(String)} return null, return false</li>
* <li>if target directory already exists, return true</li>
* <li>return {@link java.io.File#}</li>
* </ul>
*/
public static boolean makeDirs(String filePath) {
String folderName = getFolderName(filePath);
File folder = new File(folderName);
Logs.d(folder.getAbsolutePath() + " " + folder.exists());
if (folder.exists()) {
return false;
}
return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}
/**
* @param filePath
* @return
* @see #makeDirs(String)
*/
public static boolean makeFolders(String filePath) {
return makeDirs(filePath);
}
/**
* Indicates if this file represents a file on the underlying file system.
*
* @param filePath
* @return
*/
public static boolean isFileExist(String filePath) {
if (StringUtils.isBlank(filePath)) {
return false;
}
File file = new File(filePath);
return (file.exists() && file.isFile());
}
/**
* Indicates if this file represents a directory on the underlying file system.
*
* @param directoryPath
* @return
*/
public static boolean isFolderExist(String directoryPath) {
if (StringUtils.isBlank(directoryPath)) {
return false;
}
File dire = new File(directoryPath);
return (dire.exists() && dire.isDirectory());
}
/**
* delete file or directory
* <ul>
* <li>if path is null or empty, return true</li>
* <li>if path not exist, return true</li>
* <li>if path exist, delete recursion. return true</li>
* <ul>
*
* @param path
* @return
*/
public static boolean deleteFileFromPath(String path) {
if (StringUtils.isBlank(path)) {
return true;
}
File file = new File(path);
if (!file.exists()) {
return true;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
for (File f : file.listFiles()) {
if (f.isFile()) {
f.delete();
} else if (f.isDirectory()) {
deleteFileFromPath(f.getAbsolutePath());
}
}
return file.delete();
}
/**
* get file size
* <ul>
* <li>if path is null or empty, return -1</li>
* <li>if path exist and it is a file, return file size, else return -1</li>
* <ul>
*
* @param path
* @return returns the length of this file in bytes. returns -1 if the file does not exist.
*/
public static long getFileSize(String path) {
if (StringUtils.isBlank(path)) {
return -1;
}
File file = new File(path);
return (file.exists() && file.isFile() ? file.length() : -1);
}
}