最近看到一段代码每隔多少行就重新生成一个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;
}
}

1069

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



