工作中有需要就写了个校验并创建文件,进行保存数据,以防之后用到,代码可直接用!
//定义路径
private static String path = "D:/addons";
private static String filenameTemp;
public static void main(String[] args) throws IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dates = dateFormat.format(new Date());
creatTxtFile(dates);
writeTxtFile("你好");
}
/**
* 创建文件
*
* @throws IOException
*/
public static boolean creatTxtFile(String name) throws IOException {
File file = new File(path+"/js");
//校验该目录是否存在,如果存在则直接写入、否则新建文件夹并写入文件
if (!file.exists() && !file.isDirectory()) {
System.out.println("不存在");
file.mkdir();
}else {
System.out.println("目录存在");
}
boolean flag = false;
//在这里注意file是\斜杠,得通过\\进行转换
filenameTemp = file+"\\" + 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 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);
// System.getProperty("line.separator")
// 行与行之间的分隔符 相当于“\n”
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buf.toString().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;
}