java基础之文件操作
文件操作工具类(关于文件创建、写入、删除)
package util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* 文件操作工具类(关于文件创建、写入、删除)
*
* @ClassName: FileUtil
* @Description:
* @author wxy
* @date 2018年3月15日 下午3:03:54
*
*/
public class FileUtil {
//生成文件路径
private static String filePath = "G:\\WEBCOPY\\";
//文件路径+名称
private static String filePathAndName;
/**
* 创建文件
*
* @Title: createFile
* @Description:
* @param @param fileName 文件名称
* @param @param FileContent 文件内容
* @param @param fileType 文件类型
* @param @return 是否创建成功,成功则返回true
* @return boolean
* @throws
*/
public static boolean createFile(String fileName,String fileContent,String fileType){
Boolean bool = false;
filePathAndName = filePath+fileName+"."+fileType;
File file = new File(filePathAndName);
try {
//如果文件不存在,则创建新的文件
if(!file.exists()){
file.createNewFile();
bool = true;
System.err.println("success to create file:"+filePathAndName);
//文件创建成功后,向文件写入数据
writeFileContent(filePathAndName,fileContent);
}
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
/**
* 向文件写入内容
*
* @Title: writeFileContent
* @Description:
* @param @param filePath
* @param @param fileContent
* @param @return
* @return boolean
* @throws
*/
public static boolean writeFileContent(String filePath,String fileContent){
Boolean bool = false;
String filein = fileContent+"\r\n";//新写入的行,换行
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filePath);//文件路径(包括文件名称)
//将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();
//文件原有内容
for(int i=0;(temp=br.readLine())!=null;i++){
buffer.append(temp);
//行与行之间的分隔符相当于"\n"
buffer = buffer.append(System.getProperty("line.separator"));
}
buffer.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buffer.toString().toCharArray());
pw.flush();
bool = true;
} catch (Exception e) {
e.printStackTrace();
}
try {
if(pw!=null){
pw.close();
}
if(fos!=null){
fos.close();
}
if(br!=null){
br.close();
}
if(isr!=null){
isr.close();
}
if(fis!=null){
fis.close();
}
} catch (Exception e) {
}
return bool;
}
/**
* 删除文件
*
* @Title: delFile
* @Description:
* @param @param filePath 文件路径+名称+文件类型
* @param @return
* @return boolean
* @throws
*/
public static boolean delFile(String filePath){
Boolean bool = false;
File file = new File(filePath);
try {
if(file.exists()){
file.delete();
bool = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
}
还没有评论,来说两句吧...