Java 如果目录不存在,则创建一个目录,然后也在该目录中创建文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28947250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:03:17  来源:igfitidea点击:

Create a directory if it does not exist and then create the files in that directory as well

javajava-io

提问by Sri

Condition is if directory exists it has to create files in that specific directory with out creating a new directory.

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

The below code only creating a file with new directory but not for existing directory . For example the directory name would be like "GETDIRECTION"

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

采纳答案by Aaron D

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp()and getClassName()will work. You should also do something with the possible IOExceptionthat can be thrown when using any of the java.io.*classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that idis of type String- I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a Stringbefore using it in the fileName as I have done here.

此代码首先检查目录是否存在,如果不存在则创建它,然后创建文件。请注意,我无法核实你的一些方法调用,因为我没有你完整的代码,所以我假设的东西,如电话getTimeStamp()getClassName()将工作。您还应该对IOException使用任何java.io.*类时可能抛出的可能性做一些事情- 编写文件的函数应该抛出此异常(并在其他地方处理),或者您应该直接在方法中执行此操作。另外,我假设它id是类型的String- 我不知道,因为您的代码没有明确定义它。如果它是其他类似 an 的东西int,您可能应该String像我在这里所做的那样在 fileName 中使用它之前将其转换为 a 。

Also, I replaced your appendcalls with concator +as I saw appropriate.

另外,我用我认为合适的或替换了您的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);
    }
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the /in the filenames. For full portability, you should probably use something like File.separatorto construct your paths.

如果您想在 Microsoft Windows 上运行代码,您可能不应该使用这样的裸路径名 - 我不确定它会如何处理/文件名中的 。为了完全可移植性,您可能应该使用File.separator 之类的东西来构建您的路径。

Edit: According to a comment by JosefScriptbelow, it's not necessary to test for directory existence. The directory.mkdir()call will return trueif it created a directory, and falseif it didn't, including the case when the directory already existed.

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

回答by Mukesh

code:

代码:

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


}

回答by Pytry

I would suggest the following for Java8+.

我会为 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();
}

回答by Jacob R

Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:

试图使这尽可能简短和简单。如果目录不存在,则创建目录,然后返回所需的文件:

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

回答by Saikat

Using java.nio.Pathit would be quite simple -

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

回答by Dr. X

If you create a web based application, the better solution is to check the directory exists or not then create the file if not exist. If exists, recreate again.

如果您创建基于 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;
   }

回答by Inês Gomes

java 8+ version

Java 8+ 版本

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

The Files.createDirectories

Files.createDirectories

creates a new directory and parent directories that do not exist.

创建一个新目录和不存在的父目录。

The method does not thrown an exception if the directory already exist.

如果目录已经存在,该方法不会抛出异常。