小编典典

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

all

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

以下代码仅使用新目录创建一个文件,而不是为现有目录创建一个文件。例如,目录名称类似于“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();

阅读 67

收藏
2022-08-01

共1个答案

小编典典

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

另外,我用我认为合适的or替换了您的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之类的东西来构建您的路径。

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

2022-08-01