txt写入工具类
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class TxtWriter {
private static String path = "D:/html/";
private static String filenameTemp;
public static void main(String\[\] args) throws IOException {
// TxtWriter.creatTxtFile(“你好”);
TxtWriter.writeTxtFile(“test”,”helloworld”);
}
/**
* 创建文件
*
* @throws IOException
*/
public static boolean creatTxtFile(String name) throws IOException {
boolean flag = false;
filenameTemp = path + name + ".txt";
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
return flag;
}
/**
* 写文件
*
* @param newStr
* 新内容
* @throws IOException
*/
public static boolean writeTxtFile(String name,String content) throws IOException {
// 先读取原有文件内容,然后进行写入操作
boolean flag = false;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// 文件路径
filenameTemp = path + name + ".html";
File file = new File(filenameTemp);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(content.toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
}
System.out.println("文件"+filenameTemp+"生成成功!");
return flag;
}
}