Подтвердить что ты не робот

Создайте каталог, если он не существует, а затем создайте файлы в этом каталоге

Условие - если существует каталог, он должен создавать файлы в этом конкретном каталоге, не создавая новый каталог.

В приведенном ниже коде создается только файл с новым каталогом, но не для существующего каталога. Например, имя каталога будет похоже на "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();
4b9b3361

Ответ 1

Этот код сначала проверяет наличие каталога и создает его, если нет, и затем создает файл. Обратите внимание, что я не мог проверить некоторые вызовы методов, так как у меня нет полного кода, поэтому я предполагаю, что вызовы на такие вещи, как getTimeStamp() и getClassName(), будут работать. Вы также должны сделать что-то с возможным IOException, которое может быть выбрано при использовании любого из классов java.io.* - либо ваша функция, которая пишет файлы, должна выбросить это исключение (и оно будет обрабатываться в другом месте), либо вы должны сделать это в метод напрямую. Кроме того, я предположил, что id имеет тип String - я не знаю, как ваш код явно не определяет его. Если это что-то вроде int, вы должны, скорее всего, применить его к 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);
    }
}

Вероятно, вы не должны использовать такие имена, как это, если вы хотите запустить код в Microsoft Windows - я не уверен, что он будет делать с / в именах файлов. Для полной переносимости вы должны, вероятно, использовать что-то вроде File.separator для создания своих путей.

Изменить: согласно комментарию JosefScript ниже, нет необходимости проверять существование каталога. Вызов directory.mkdir() возвращает true, если он создал каталог, и false, если это не так, включая случай, когда каталог уже существует.

Ответ 2

Я бы предложил следующее для 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();
}

Ответ 3

Попытка сделать это как можно более коротким и простым. Создает каталог, если он не существует, а затем возвращает нужный файл:

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

Ответ 4

код:

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


}

Ответ 5

Используя 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);
    }