java - 创建新目录

标签 java file-io

我坚持没有创建文件夹的事实。

private static File createNewTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseNamePrefix = System.currentTimeMillis() + "_" + Math.random() + "-";
LOG.info(System.getProperty("java.io.tmpdir"));
File tempDir = new File(baseDir, baseNamePrefix + "0");
LOG.info(tempDir.getAbsolutePath());

tempDir.mkdirs();

if (tempDir.exists()) {
  LOG.info("I would be happy!");
}
else {
  LOG.info("No folder there");
}
return tempDir;
}

有什么问题吗?我可以得到日志,那里没有文件夹...

最佳答案

您的代码没问题,但您的条件错误:

if (tempDir.exists()) {
  LOG.info("I would be happy!");
}
else {
  LOG.info("No folder there");
}

该文件夹确实已创建,您可以通过获取路径并在资源管理器中打开来检查该文件夹。

编辑:它至少可以在 Windows 上运行。我把它清理了一下:

   public static void main() {
        File baseDir = new File(System.getProperty("java.io.tmpdir"));
        File tempDir = new File(baseDir, "test0");
        System.err.println(tempDir.getAbsolutePath());

        tempDir.mkdir();

        System.err.println("is it a dir? " + tempDir.isDirectory());
        System.err.println("does it exist? " + tempDir.exists());
    }

输出:

C:\Users\marsch1\AppData\Local\Temp\test0 is it a dir? true does it exist? true

关于java - 创建新目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9004275/

相关文章:

java - 为 Spring 配置 Weblogic 11g

java - 如何为 GridBagLayout 设置约束

Java 强制转换(强制转换运算符表达式)

C++ FileIO 读取和写入对象变量

file - 如何检查 ReadFileEx 是否在没有休眠线程的情况下结束加载?

java - 与逐行读取相比,将整个文件读取到单个字符串中有何优点和缺点?

java - 如何使用 Java 的正则表达式查找 (* comments *)?

java - 如何扫描整个 C 盘的播放列表

sql - 从 oracle 数据库表中生成带有自定义 XML 标记的 XML 文件

java - java写文件时出现空指针异常