您的位置:首页 > 其它

如何按日期增量生成文件

2015-06-08 23:09 309 查看
最近看到一段代码每隔多少行就重新生成一个TXT文件,同时生成的文件名在按当天的日期增量的,不生成重复的文件名。

之前看见其他人使用了递归调用,这边我自己写了一段代码如下:

import java.io.File;

import java.io.IOException;

public class GetNewFileByDate {

public static void main(String[] args) {
String date = "20150608";
String path = "D:\\java-test\\";
File file = new File(path + getFileName(path,date));
try {
if(file.createNewFile()){
System.out.println(file.getAbsolutePath() + "创建成功");
}else{
System.out.println(file.getAbsolutePath() + "创建失败");
}
} catch (IOException e) {

e.printStackTrace();
}
}

/**
* 根据日期获得文件名
* @param date
* @return
*/
public static String getFileName(String path,String date){
int serial = 0;
String fileName = date + getSerialByCurrentID(1,serial);

//文件存在重新计算
while( (new File(path + fileName)).exists() ){
fileName =  date + getSerialByCurrentID(1,++serial);
}

return fileName;

}

/**
* 获取下一个序列
* @param digit
* @param currentSerial
* @return
*/
public static String getSerialByCurrentID(int digit,int currentSerial){
String nextSerial = "";
String zero;
int raise = 0;
String temp = String.valueOf(++currentSerial);
//参数错误都返回序列+1
if(digit < 0 || currentSerial < 0){

nextSerial = temp ;

}else{
zero = "0";
raise = digit - temp.length();
for(int i = 0 ;i < raise; i++){
nextSerial += zero;
}

nextSerial += temp;
}

return nextSerial;
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: