我正在尝试使用java nio创建一个新文件,我遇到了一个createFile错误.错误看起来像这样:
createFile error: java.nio.file.NoSuchFileException: /Users/jchang/result_apache_log_parser_2015/06/09_10:53:49
Run Code Online (Sandbox Code Playgroud)
代码段看起来像这样:
String filename = "/Users/jchang/result_apache_log_parser_" + filename_date;
Path file = Paths.get(filename);
try {
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
System.err.format("createFile error: %s%n", x);
}
Run Code Online (Sandbox Code Playgroud)
任何人都知道如何解决这个问题?谢谢你的帮助!
小智 7
我会说Turing85是正确的.你的filename_date变量中有斜杠.所以/Users/jchang/result_apache_log_parser_2015必须作为目录存在.这是NoSuchFileException缺少目录的原因.
您的代码至少有两个问题。首先:您的文件名中有路径分隔符 ( /)。第二:至少在 Windows 下,您的解决方案在文件名 ( :) 中包含非法字符。
要解决第一个问题,您可以走两条路线:a) 创建您需要的所有文件夹或 b) 将分隔符更改为不同的内容。我将解释两者。
要将所有文件夹创建到一个路径,您只需调用
Files.createDirectories(path.getParent());
Run Code Online (Sandbox Code Playgroud)
path文件在哪里(重要!)。通过调用getParent()文件,我们得到文件夹,其中path所在。Files.createDirectories(...)照顾其余的。
b) 更改分隔符:没有比这更容易的了:
String filename = "/Users/jchang/result_apache_log_parser_"
+ filename_date.replace("/", "_")
.replace(":", "_");
Run Code Online (Sandbox Code Playgroud)
这应该产生类似 /User/jchang/result_apache_parser_2015_06_09_10_53_29
b) 我们也解决了第二个问题。
现在让我们将它们组合在一起并应用一些小技巧nio:
String filename = "/Users/jchang/result_apache_log_parser_"
+ filename_date.replace('/', '_')
.replace(':', '_');
Path file = Paths.get(filename);
try {
// Create sub-directories, if needed.
Files.createDirectories(file.getParent());
// Create the file content.
byte[] fileContent = ...;
// We do not need to create the file manually, let NIO handle it.
Files.write(file
, fileContent
// Request permission to write the file
, StandardOpenOption.WRITE
// If the file exists, append new content
, StandardOpenOption.APPEND
// If the file does not exist, create it
, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,nio请单击此处。
正如许多人所说,您需要创建中间目录,例如 ../06/..
因此,在创建文件之前使用它来创建不存在的目录,
Files.createDirectories(mPath.getParent());
Run Code Online (Sandbox Code Playgroud)
所以你的代码应该是:
Path file = Paths.get(filename);
try {
Files.createDirectories(file.getParent());
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
System.err.format("createFile error: %s%n", x);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6162 次 |
| 最近记录: |