holmos.webtest.basetools.file.MyFile Maven / Gradle / Ivy
package holmos.webtest.basetools.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author 吴银龙([email protected])
* */
public class MyFile {
private String filePath;
File file;
public MyFile(String filePath){
this.filePath=filePath;
this.file=new File(filePath);
if(!file.exists()){
createFile(filePath);
}
}
public MyFile(File file){
this.filePath=file.getAbsolutePath();
this.file=file;
}
/**根据指定文件地址新建文件,如果有多级目录没有建立,那么建立中间目录*/
public static boolean createDictory(String path){
if(!new File(path).exists()){
return new File(path).mkdirs();
}return true;
}
/**
* 跨目录级别建立文件
* */
public static boolean createFile(String path){
if(!new File(path).exists()){
StringBuilder dictoryPath=new StringBuilder(path);
dictoryPath.delete(path.lastIndexOf('\\'), path.length());
createDictory(dictoryPath.toString());
try {
new File(path).createNewFile();
} catch (IOException e) {
System.out.println("文件创建失败!");
}
}return true;
}
public static boolean exist(String path){
return new File(path).exists();
}
public String getFileContentByString(){
ListfileContentList=getFileContentByList();
StringBuilder content=new StringBuilder();
for(String str:fileContentList){
content.append(str);
}return content.toString();
}
public ArrayListgetFileContentByList(){
if(!new File(filePath).exists())
return null;
ArrayListfileContent=new ArrayList();
try {
BufferedReader reader=new BufferedReader(new FileReader(new File(filePath)));
String temp;
while((temp=reader.readLine())!=null){
fileContent.add(temp.trim());
}
reader.close();
return fileContent;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void setFileContent(ArrayListcontent){
MyWriter writer=new MyWriter(filePath);
StringBuilder tab=new StringBuilder();
for(int i=0;i