java创建txt⽂件并存⼊内容本⽂实例为⼤家分享了java创建txt⽂件并存⼊内容的具体代码,供⼤家参考,具体内容如下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;
public class txtExport {
private static String path = "D:/";
private static String filenameTemp;
public static void main(String[] args) throws IOException {
txtExport.writeTxtFile("你好");
}
/**
* 创建⽂件
*
* @throws IOException
*/
public static boolean creatTxtFile(String name) throws IOException {
boolean flag = false;
filenameTemp = path + name + ".txt";
File filename = new File(filenameTemp);
if (!ists()) {
flag = true;
}
return flag;
}
/**
* 写⽂件
*
* @param newStr
*      新内容
* @throws IOException
*/
public static boolean writeTxtFile(String newStr) throws IOException {
// 先读取原有⽂件内容,然后进⾏写⼊操作
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// ⽂件路径
File file = new File(filenameTemp);
// 将⽂件读⼊输⼊流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该⽂件原有的内容
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
// Property("line.separator")
// ⾏与⾏之间的分隔符相当于“\n”
buf = buf.Property("line.separator"));
}
java创建文件buf.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.String().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
// TODO ⾃动⽣成 catch 块
throw e1;
} finally {
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();
}
}
return flag;
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。