代码如下:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author shearmin
* @classname FileCreate
* @description
* @date 2018年11月20日 下午3:56:56
*/
public class FileCreate {
@SuppressWarnings("resource")
public static void main(String[] args) {
FileWriter fw=null;
//文件路径
String filePath="D:\\fileCreate";
//日期格式
SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH_MM_SS");
SimpleDateFormat dfTime = new SimpleDateFormat("yyyy-MM-dd:HH:MM:SS ");
String fileName=df.format(new Date())+".txt";
File newFile=new File(filePath);
if(!newFile.exists()) {
newFile.mkdir();
}
File f=new File(filePath,fileName);
try {
//创建文件
f.createNewFile();
fw=new FileWriter(f);
//写入数据
fw.write(dfTime.format(new Date())+"Coding change the word");
} catch (IOException e) {
throw new RuntimeException("文件创建失败");
}finally {
try {
fw.close();
} catch (IOException e) {
throw new RuntimeException("文件流关闭失败");
}
}
}
}
结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/adca6f6f1ba1671a58126093454cc2f0.png)