Java代码实现新建文件并写入内容的工具类,内容如下:
package lc.util;
import org.apache.commons.lang.StringUtils;
import java.io.*;
/**
* @author : https://www.yomige.org/
*/
public class FileUtil {
/**
* 创建文件
*
* @param fileFullPath 文件完整路径,包括文件名
* @return 创建成功为true
*/
public static boolean creatNewFile(String fileFullPath) {
try {
File filename = new File(fileFullPath);
if (!filename.exists()) {
return filename.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 写文件
*
* @param content 新内容
* @param fileFullPath 文件完整路径,包括文件名
* @param isOverwrite 是否覆盖原来内容,false表示追加
* @throws IOException 异常
*/
public static boolean writeTxtFile(String content, String fileFullPath, Boolean isOverwrite) throws IOException {
if (!new File(fileFullPath).exists()) {
System.out.println("写入文件失败,文件或目录不存在");
return false;
}
if (new File(fileFullPath).isDirectory()) {
System.out.println("写入文件失败,请指定文件名!");
return false;
}
content = content + "\r\n";
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
FileOutputStream fileOutputStream = null;
PrintWriter pw = null;
try {
// 文件路径
File filePath = new File(fileFullPath);
StringBuffer newFileStringBuffer = new StringBuffer();
if (!isOverwrite) {
// 将文件读入输入流
fileInputStream = new FileInputStream(filePath);
inputStreamReader = new InputStreamReader(fileInputStream);
bufferedReader = new BufferedReader(inputStreamReader);
// 读取原有的内容
String line = null;
while (bufferedReader.ready()) {
line = bufferedReader.readLine();
newFileStringBuffer = newFileStringBuffer.append(line);
// 行与行之间的分隔符 相当于“\n”
newFileStringBuffer = newFileStringBuffer.append(System.getProperty("line.separator"));
}
}
//追加新内容
newFileStringBuffer.append(content);
fileOutputStream = new FileOutputStream(filePath);
pw = new PrintWriter(fileOutputStream);
pw.write(newFileStringBuffer.toString().toCharArray());
pw.flush();
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (pw != null) {
pw.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (fileInputStream != null) {
fileInputStream.close();
}
}
return true;
}
}
更新:上面的writeTxtFile()方法写入中文可能存在乱码问题,参考这个方法:https://ych0108.iteye.com/blog/2228834 ,具体代码修改为下方
修改前:
fileOutputStream = new FileOutputStream(filePath);
pw = new PrintWriter(fileOutputStream);
pw.write(newFileStringBuffer.toString().toCharArray());
pw.flush();
修改后:
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
BufferedWriter writer = new BufferedWriter(write);
writer.write(newFileStringBuffer.toString());
writer.close();
最新评论
不错挺好用的,东至梅城何红涛林场的 何红涛2个月前 (10-18)回复
识别码不对
呵呵
我的是ipv4网络,如何使用直播源啊!