创建一个不存在的目录,然后创建该目录中的文件

条件是,如果目录存在,则必须在该特定目录中创建文件,而无需创建新目录。

下面的代码只创建一个包含新目录的文件,而不包含现有目录。例如,目录名类似于“ 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();


433591 次浏览

这段代码首先检查目录是否存在,如果不存在则创建目录,然后再创建文件。请注意,我无法验证您的一些方法调用,因为我没有您的完整代码,所以我假设类似 getTimeStamp()getClassName()的调用将工作。您还应该对在使用任何 java.io.*类时可能抛出的 IOException进行处理——要么您的写入文件的函数应该抛出此异常(并在其他地方进行处理) ,要么您应该直接在方法中进行处理。另外,我假设 idString类型的——我不知道,因为您的代码没有明确定义它。如果它是类似于 int的东西,那么在在 fileName 中使用它之前,您可能应该将它强制转换为 String,就像我在这里所做的那样。

另外,我用我认为合适的 concat+代替了您的 append呼叫。

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);
}
}

如果你想在 Microsoft Windows 上运行代码,你可能不应该使用这样的裸路径名称-我不确定它会对文件名中的 /做什么。为了实现完全的可移植性,您可能应该使用类似于 文件,分隔符的东西来构造您的路径。

编辑 : 根据下面 JosefScript的注释,没有必要测试目录的存在。如果创建了一个目录,directory.mkdir()调用将返回 true,如果没有,返回 false,包括目录已经存在的情况。

密码:

// 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);




}

对于 Java8 + ,我建议采用以下方法。

/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
public File createOrRetrieve(final String target) throws IOException {
final File answer;
Path path = Paths.get(target);
Path parent = path.getParent();
if(parent != null && Files.notExists(parent)) {
Files.createDirectories(path);
}
if(Files.notExists(path)) {
LOG.info("Target file \"" + target + "\" will be created.");
answer = Files.createFile(path).toFile();
} else {
LOG.info("Target file \"" + target + "\" will be retrieved.");
answer = path.toFile();
}
return answer;
}

编辑: 更新修复 bug,如@Cataclym 和@Marcono1234所示

尽量简短点。创建不存在的目录,然后返回所需的文件:

/** 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);
}

使用 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);
}

如果你创建一个基于 web 的应用程序,更好的解决方案是检查目录是否存在,如果目录不存在则创建文件。如果存在,重新创建。

    private File createFile(String path, String fileName) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(".").getFile() + path + fileName);


// Lets create the directory
try {
file.getParentFile().mkdir();
} catch (Exception err){
System.out.println("ERROR (Directory Create)" + err.getMessage());
}


// Lets create the file if we have credential
try {
file.createNewFile();
} catch (Exception err){
System.out.println("ERROR (File Create)" + err.getMessage());
}
return  file;
}

Java8 + 版本:

Files.createDirectories(Paths.get("/Your/Path/Here"));

Files.createDirectories()创建一个新目录和一个不存在的父目录。如果目录已经存在,则此方法不引发异常。

一个使用 Java8的简单解决方案

public void init(String multipartLocation) throws IOException {
File storageDirectory = new File(multipartLocation);


if (!storageDirectory.exists()) {
if (!storageDirectory.mkdir()) {
throw new IOException("Error creating directory.");
}
}
}

如果您使用的是 Java8或更高版本,那么 Files.createDirectories()方法的效果最好。