我想生成一个用当前日期生成一个文件,请问我该怎样做,再线等
我想生成一个txt文件,文件的名称要取当前日期,格式为:group1_log_20050515,还需要指定一下这个文件的生成路径,比如c://
请问我该如何实现它,谢谢各位帮帮忙!!!!
------解决方案--------------------import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileTest {
public static void main(String[] args) {
a.createFile( "c: ", "this is a testfile! ");
}
/**
* 新建文件
* @param filePathAndName 文本文件完整绝对路径及文件名
* @param fileContent 文本文件内容
* @return
*/
public static void createFile(String filePath,String fileContent) {
try {
//组成文件名
SimpleDateFormat formatter = new SimpleDateFormat( "yyyyMMdd ");
String dateFileName = formatter.format(new Date());
String path = filePath+ "\\group1_log_ "+dateFileName+ ".txt ";
filePath = filePath.toString();
File myFilePath = new File(path);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
resultFile.close();
System.out.println( "create file ok! ");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
------解决方案--------------------public class Wtrite
{
public Wtrite()
{
}
public static void main (String stc[])
{
FileOutputStream outStream = null;
BufferedWriter writer = null;
String time = " ";
SimpleDateFormat format = new SimpleDateFormat( "yyymmdd ");
GregorianCalendar calendar = new GregorianCalendar();
time = format.format(calendar.getTime());
try {
int i = 0;
outStream = new FileOutputStream( "c:\\group1_log_ " + time + ".txt ");
writer = new BufferedWriter(new OutputStreamWriter(outStream));
String dateLine = "test ";
writer.write(dateLine);
writer.newLine();
writer.flush();
} catch (Exception e){
System.out.println(e);
}finally {
try{
if (writer != null) {
writer.close();
}
if (outStream != null) {
outStream.close();
}
}catch (Exception e){
System.out.println(e);
}
}
}