我需要在特定目录中的当前时间戳名称中创建一个文本文件
D:\ Assignments \ abassign in java。
但是当我尝试这样做时,会出现以下错误,因为文件名不应包含':'。但时间戳包含':'
线程中的异常" main" java.io.IOException:文件名,目录名或卷标语法不正确 在java.io.WinNTFileSystem.createFileExclusively(本机方法) 在java.io.File.createNewFile(File.java:883) 在abassign.Abassign.main(Abassign.java:35) Java结果:1
此错误显示
答案 0 :(得分:2)
我使用这样的东西:
StringBuffer fn = new StringBuffer();
fn.append(workingDirectory);
fn.append("/");
fn.append("fileNamePrefix-");
fn.append("-");
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
fn.append(df.format(new Date()));
fn.append("-fileNamePostFix.txt");
return fn.toString();
(当然,您可以删除前缀,后缀和workingDirectory部分)
答案 1 :(得分:1)
如果您在Windows上,您的文件名不能包含:
,则需要将其替换为其他字符...
保留以下字符:
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
例如:
String yourTimeStamp = "01-01-2016 17:00:00";
File yourFile = new File("your directory", yourTimeStamp.replace(":", "_"));
答案 2 :(得分:0)
这是使用时间戳生成文件的代码
/*
* created by Sandip Bhoi 9960426568
*/
package checkapplicationisopen;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Random;
public class GeneratorUtil {
/**
*
* @param args
*/
public static void main(String args[])
{
GeneratorUtil generatorUtil=new GeneratorUtil();
generatorUtil.createNewFile("c:\\Documents", "pdf");
}
/**
*
* @param min
* @param max
* @return
*/
public static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
/**
*
* @param prefix adding the prefix for time stamp generated id
* @return the concatenated string with id and prefix
*/
public static String getId(String prefix)
{
java.util.Date date = new java.util.Date();
String timestamp = new Timestamp(date.getTime()).toString();
String dt1 = timestamp.replace('-', '_');
String dt2 = dt1.replace(' ', '_');
String dt3 = dt2.replace(':', '_');
String dt4 = dt3.replace('.', '_');
int temp = randInt(1, 5000);
return prefix +"_"+ temp + "_" + dt4;
}
/**
*
* @param direcotory
* @param extension
*/
public void createNewFile(String direcotory,String extension)
{
try {
File file = new File(direcotory+"//"+getId("File")+"."+extension);
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}