使用名称中的变量创建新文件名

问题描述:

尝试在名称中使用变量的特定目录中创建文件。但是,我在以下几行保留get和IOException。使用名称中的变量创建新文件名

File dir = new File("logs/" + s); 
dir.mkdirs(); 
File permfile = new File(dir, stamp + ".txt"); 
permfile.createNewFile(); 
boolean exist = permfile.createNewFile(); 

我感谢您的指导。我今天已经在这12小时了,一旦我能写出我可以回家的文件! :)

+0

究竟是哪一行抛出IOException? – gobernador 2012-03-12 02:37:50

+0

This one:File permfile = new File(dir,stamp +“.txt”); – 2012-03-12 02:45:47

+0

并道歉,累了。它是:permfile.createNewFile();这将表明该文件已存在,但它不是 – 2012-03-12 02:49:04

编辑: SRY似乎是对我来说有点晚,但想你的代码,它的工作完美,也不例外抛出:

  try{ 
      String s = "foldername"; 
      String stamp = "filename"; 
      File dir = new File("logs/" + s); 
      dir.mkdirs(); 
      File permfile = new File(dir, stamp + ".txt"); 
      permfile.createNewFile(); 
      } 
      catch(Exception k) 
      { System.out.println("Oops");} 

也许错误是别的地方?

+0

谢谢。也试过了。没有运气 – 2012-03-12 02:51:47

根据javadocs File createNewFile()抛出一个Checked Exception。

更多checked vs unchecked exception

是某种类型的I/O异常发生了I/OException信号。

试试下面的代码:

 try{ 
      String s = "foldername"; 
      String fName = "filename"; 
      File dir = new File("logs/" + s); 
      dir.mkdirs(); 
      File permfile = new File(dir + fName + ".txt"); 
      permfile.createNewFile(); 
      } 
      catch(Exception e) 
      { 
      e.printStackTrace(); 
      } 

粘贴错误日志中如果发生,它会帮助你找到原因。

一个可能的问题,我可以看到的是用一个文字向前斜线作为路径分隔符,当Windows使用斜线。您的系统可能会将正斜杠解释为名称的一部分,而不是分隔符,而在Windows中正斜杠是illegal character for a filename

要避免此问题完全,我将让Java API的搜索结果排序方式(你自己,而不是构建字面路径),使用适当的构造函数new File(String parent, String child)您的目录文件分隔符,即:

File dir = new File("logs", s); 

的其他问题是stamp可能包含文件系统中文件名不合法的字符。

我会用NIO API这样的任务。

Path dir = Paths.get("logs", s); 
Files.createDirectories(dir); 
Path permfile = dir.resolve(stamp + ".txt"); 
boolean exist = true; 
if(!permfile.toFile().exists()) { 
    Files.createFile(permfile); 
    exist = false; 
}