条件是如果目录存在,它必须在该特定目录中创建文件而不创建新目录.
以下代码仅创建具有新目录但不适用于现有目录的文件.例如,目录名称将类似于"GETDIRECTION"
String PATH = "/remote/dir/server/";
String fileName = PATH.append(id).concat(getTimeStamp()).append(".txt");
String directoryName = PATH.append(this.getClassName());
File file = new File(String.valueOf(fileName));
File directory = new File(String.valueOf(directoryName));
if(!directory.exists()){
directory.mkdir();
if(!file.exists() && !checkEnoughDiskSpace()){
file.getParentFile().mkdir();
file.createNewFile();
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
Run Code Online (Sandbox Code Playgroud)
Inê*_*mes 148
Java 8+ 版本:
Files.createDirectories(Paths.get("/Your/Path/Here"));
Run Code Online (Sandbox Code Playgroud)
在Files.createDirectories()创建不存在的一个新的目录和父目录。如果目录已经存在,此方法不会抛出异常。
Aar*_*n D 123
此代码首先检查目录是否存在,如果没有则创建它,然后创建该文件.请注意,我无法验证您的一些方法调用,因为我没有完整的代码,所以我假设调用类似的东西getTimeStamp()并且getClassName()会起作用.您还应该对IOException使用任何java.io.*类时可能引发的可能做一些事情- 编写文件的函数应抛出此异常(并在其他地方处理),或者您应该直接在方法中执行此操作.此外,我假设id是类型String- 我不知道,因为您的代码没有明确定义它.如果它是一个类似的东西int,你可能应该把它转换为a String之前在fileName中使用它,就像我在这里所做的那样.
另外,我append用concat或+正如我认为的那样取代你的电话.
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想在Microsoft Windows上运行代码,你可能不应该使用像这样的裸路径名 - 我不确定它将/在文件名中做什么.为了完全可移植性,您应该使用File.separator之类的东西来构建路径.
编辑:根据JosefScript的评论,没有必要测试目录的存在.如果它创建了一个目录,则该directory.mkdir() 调用将返回true,false如果没有,则包括该目录已存在的情况.
Jac*_*b R 20
试图尽可能简短.如果目录不存在,则创建目录,然后返回所需的文件:
/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return new File(directory + "/" + filename);
}
Run Code Online (Sandbox Code Playgroud)
Pyt*_*try 17
我建议Java8 +以下内容.
/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
private File createOrRetrieve(final String target) throws IOException{
final Path path = Paths.get(target);
if(Files.notExists(path)){
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(Files.createDirectories(path)).toFile();
}
LOG.info("Target file \"" + target + "\" will be retrieved.");
return path.toFile();
}
/**
* Deletes the target if it exists then creates a new empty file.
*/
private File createOrReplaceFileAndDirectories(final String target) throws IOException{
final Path path = Paths.get(target);
// Create only if it does not exist already
Files.walk(path)
.filter(p -> Files.exists(p))
.sorted(Comparator.reverseOrder())
.peek(p -> LOG.info("Deleted existing file or directory \"" + p + "\"."))
.forEach(p -> {
try{
Files.createFile(Files.createDirectories(p));
}
catch(IOException e){
throw new IllegalStateException(e);
}
});
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(
Files.createDirectories(path)
).toFile();
}
Run Code Online (Sandbox Code Playgroud)
小智 5
码:
// Create Directory if not exist then Copy a file.
public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {
Path FROM = Paths.get(origin);
Path TO = Paths.get(destination);
File directory = new File(String.valueOf(destDir));
if (!directory.exists()) {
directory.mkdir();
}
//overwrite the destination file if it exists, and copy
// the file attributes, including the rwx permissions
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(FROM, TO, options);
}
Run Code Online (Sandbox Code Playgroud)
使用java.nio.Path它会很简单 -
public static Path createFileWithDir(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return Paths.get(directory + File.separatorChar + filename);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
175862 次 |
| 最近记录: |