Java代码实现新建文件并写入内容的工具类,内容如下:
package lc.util;
import org.apache.commons.lang.StringUtils;
import java.io.*;
/**
* @author : https://www.4spaces.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();
最新评论
网飞没问题, 迪士尼+有解决方案么?
pp助手是安卓手机用的,根本下载用不来苹果
已解决
这样的话数据库里的结构为{"attachment":{"content":"xxx"}}, 要怎么才能变成{"content":"xxx"},从而使结构保持一致?
赞! make test不过的坑都写到的,谢谢楼主~
谢谢你
用了root用户还是一直502是怎么回事呢
student id 是空的