Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
// yyyyMMddHHmmssSSSXXXX
String fileNameString = sdf.format(date)
+ String.valueOf(Math.random() * 10000).subString(0, 4);
File fileDirPathFile = new File("G:/user/test/");
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("a");
sBuffer.append("b");
String txtNeiRong = sBuffer.toString();
if (!fileDirPathFile.exists()) {
fileDirPathFile.mkdirs();
}
String filePathAndName = "G:/user/test/yyyyMMddHHmmssSSSXXXX.tmp";
String filePathAndName1 = "G:/user/test/yyyyMMddHHmmssSSSXXXX.txt";
FileOutputStream fosFileOutputStream = new FileOutputStream(
filePathAndName);
OutputStreamWriter osw = new OutputStreamWriter(fosFileOutputStream,
"UTF-8");
osw.write(txtNeiRong);
osw.write("");
osw.close();
fosFileOutputStream.close();
File tmpFile = new File(filePathAndName);
File txtFile = new File(filePathAndName1);
tmpFile.renameTo(txtFile);
这篇博客介绍了如何使用Java动态生成包含特定内容的临时文件(.tmp),然后将其转换为.txt文件。通过设置日期时间戳和随机数作为文件名,确保文件的独特性。文件操作包括创建目录、写入字符串内容以及使用FileOutputStream和OutputStreamWriter处理文件编码。最后通过renameTo方法将.tmp文件重命名为.txt文件。
952

被折叠的 条评论
为什么被折叠?



