java.io.File.mkdir()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.8k)|赞(0)|评价(0)|浏览(123)

本文整理了Java中java.io.File.mkdir()方法的一些代码示例,展示了File.mkdir()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.mkdir()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:mkdir

File.mkdir介绍

[英]Creates the directory named by this file, assuming its parents exist. Use #mkdirs if you also want to create missing parents.

Note that this method does not throw IOException on failure. Callers must check the return value. Note also that this method returns false if the directory already existed. If you want to know whether the directory exists on return, either use (f.mkdir() || f.isDirectory())or simply ignore the return value from this method and simply call #isDirectory.
[中]

代码示例

代码示例来源:origin: stackoverflow.com

File folder = new File(Environment.getExternalStorageDirectory() + "/map");
boolean success = true;
if (!folder.exists()) {
  success = folder.mkdir();
}
if (success) {
  // Do something on success
} else {
  // Do something else on failure 
}

代码示例来源:origin: thinkaurelius/titan

private static File getSubDirectory(String base, String sub) {
  File subdir = new File(base, sub);
  if (!subdir.exists()) {
    if (!subdir.mkdir()) {
      throw new IllegalArgumentException("Cannot create subdirectory: " + sub);
    }
  }
  assert subdir.exists() && subdir.isDirectory();
  return subdir;
}

代码示例来源:origin: redisson/redisson

/**
 * Creates single folders.
 */
public static void mkdir(File dir) throws IOException {
  if (dir.exists()) {
    if (!dir.isDirectory()) {
      throw new IOException(MSG_NOT_A_DIRECTORY + dir);
    }
    return;
  }
  if (!dir.mkdir()) {
    throw new IOException(MSG_CANT_CREATE + dir);
  }
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Creates a directory with the given prefix inside the Alluxio temporary directory.
 *
 * @param prefix a prefix to use in naming the temporary directory
 * @return the created directory
 */
public static File createTemporaryDirectory(String prefix) {
 final File file = new File(ALLUXIO_TEST_DIRECTORY, prefix + "-" + UUID.randomUUID());
 if (!file.mkdir()) {
  throw new RuntimeException("Failed to create directory " + file.getAbsolutePath());
 }
 Runtime.getRuntime().addShutdownHook(new Thread(() -> delete(file)));
 return file;
}

代码示例来源:origin: testcontainers/testcontainers-java

@BeforeClass
public static void setupContent() throws FileNotFoundException {
  contentFolder.mkdir();
  contentFolder.setReadable(true, false);
  contentFolder.setWritable(true, false);
  contentFolder.setExecutable(true, false);
  File indexFile = new File(contentFolder, "index.html");
  indexFile.setReadable(true, false);
  indexFile.setWritable(true, false);
  indexFile.setExecutable(true, false);
  @Cleanup PrintStream printStream = new PrintStream(new FileOutputStream(indexFile));
  printStream.println("<html><body>This worked</body></html>");
}

代码示例来源:origin: stanfordnlp/CoreNLP

boolean createdDir = (new File(distribName)).mkdir();
if(createdDir) {
   File destFile = new File(filename);
   String relativePath = distribName + "/" + destFile.getName();
   destFile = new File(relativePath);
   FileSystem.copyFile(new File(filename),destFile);

代码示例来源:origin: apache/flink

JobArchiveFetcherTask(List<HistoryServer.RefreshLocation> refreshDirs, File webDir, CountDownLatch numFinishedPolls) {
  this.refreshDirs = checkNotNull(refreshDirs);
  this.numFinishedPolls = numFinishedPolls;
  this.cachedArchives = new HashSet<>();
  this.webDir = checkNotNull(webDir);
  this.webJobDir = new File(webDir, "jobs");
  webJobDir.mkdir();
  this.webOverviewDir = new File(webDir, "overviews");
  webOverviewDir.mkdir();
}

代码示例来源:origin: kiegroup/optaplanner

public void initBenchmarkReportDirectory(File benchmarkDirectory) {
  String timestampString = startingTimestamp.format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmss"));
  if (StringUtils.isEmpty(name)) {
    name = timestampString;
  }
  if (!benchmarkDirectory.mkdirs()) {
    if (!benchmarkDirectory.isDirectory()) {
      throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory
          + ") already exists, but is not a directory.");
    }
    if (!benchmarkDirectory.canWrite()) {
      throw new IllegalArgumentException("The benchmarkDirectory (" + benchmarkDirectory
          + ") already exists, but is not writable.");
    }
  }
  int duplicationIndex = 0;
  do {
    String directoryName = timestampString + (duplicationIndex == 0 ? "" : "_" + duplicationIndex);
    duplicationIndex++;
    benchmarkReportDirectory = new File(benchmarkDirectory,
        BooleanUtils.isFalse(aggregation) ? directoryName : directoryName + "_aggregation");
  } while (!benchmarkReportDirectory.mkdir());
  for (ProblemBenchmarkResult problemBenchmarkResult : unifiedProblemBenchmarkResultList) {
    problemBenchmarkResult.makeDirs();
  }
}

代码示例来源:origin: apache/flink

@Before
public void setUp() throws Exception {
  final File testRoot = folder.newFolder();
  checkpointDir = new File(testRoot, "checkpoints");
  savepointDir = new File(testRoot, "savepoints");
  if (!checkpointDir.mkdir() || !savepointDir.mkdirs()) {
    fail("Test setup failed: failed to create temporary directories.");
  }
}

代码示例来源:origin: stackoverflow.com

public static File createTempDirectory()
  throws IOException
{
  final File temp;

  temp = File.createTempFile("temp", Long.toString(System.nanoTime()));

  if(!(temp.delete()))
  {
    throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
  }

  if(!(temp.mkdir()))
  {
    throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
  }

  return (temp);
}

代码示例来源:origin: azkaban/azkaban

private static File createIfDoesNotExist(final String baseDirectoryPath) {
 final File baseDirectory = new File(baseDirectoryPath);
 if (!baseDirectory.exists()) {
  baseDirectory.mkdir();
  log.info("Creating dir: " + baseDirectory.getAbsolutePath());
 }
 return baseDirectory;
}

代码示例来源:origin: stanfordnlp/CoreNLP

private static void makeDir(String path) {
 File outDir = new File(path);
 if (!outDir.exists()) {
   outDir.mkdir();
 }
}

代码示例来源:origin: prestodb/presto

EmbeddedElasticsearchNode()
{
  try {
    elasticsearchDirectory = File.createTempFile("elasticsearch", "test");
    elasticsearchDirectory.delete();
    elasticsearchDirectory.mkdir();
  }
  catch (IOException e) {
    throw new UncheckedIOException(e);
  }
  Settings setting = Settings.builder()
      .put("cluster.name", "test")
      .put("path.home", elasticsearchDirectory.getPath())
      .put("path.data", new File(elasticsearchDirectory, "data").getAbsolutePath())
      .put("path.logs", new File(elasticsearchDirectory, "logs").getAbsolutePath())
      .put("transport.type.default", "local")
      .put("transport.type", "netty4")
      .put("http.type", "netty4")
      .put("http.enabled", "true")
      .put("path.home", "elasticsearch-test-data")
      .build();
  node = new ElasticsearchNode(setting, ImmutableList.of(Netty4Plugin.class));
}

代码示例来源:origin: testcontainers/testcontainers-java

@SuppressWarnings({"Duplicates", "ResultOfMethodCallIgnored"})
@BeforeClass
public static void setupContent() throws FileNotFoundException {
  contentFolder.mkdir();
  contentFolder.setReadable(true, false);
  contentFolder.setWritable(true, false);
  contentFolder.setExecutable(true, false);
  File indexFile = new File(contentFolder, "index.html");
  indexFile.setReadable(true, false);
  indexFile.setWritable(true, false);
  indexFile.setExecutable(true, false);
  @Cleanup PrintStream printStream = new PrintStream(new FileOutputStream(indexFile));
  printStream.println("<html><body>This worked</body></html>");
}

代码示例来源:origin: internetarchive/heritrix3

protected void initLaunchDir() {
  initLaunchId();
  try {
    currentLaunchDir = new File(getConfigurationFile().getParentFile(), getCurrentLaunchId());
    if (!currentLaunchDir.mkdir()) {
      throw new IOException("failed to create directory " + currentLaunchDir);
    }
    
    // copy cxml to launch dir
    FileUtils.copyFileToDirectory(getConfigurationFile(), currentLaunchDir);
    
    // attempt to symlink "latest" to launch dir
    File latestSymlink = new File(getConfigurationFile().getParentFile(), "latest");
    latestSymlink.delete();
    boolean success = FilesystemLinkMaker.makeSymbolicLink(currentLaunchDir.getName(), latestSymlink.getPath());
    if (!success) {
      LOGGER.warning("failed to create symlink from " + latestSymlink + " to " + currentLaunchDir);
    }
  } catch (IOException e) {
    LOGGER.log(Level.SEVERE, "failed to initialize launch directory: " + e);
    currentLaunchDir = null;
  }
}

代码示例来源:origin: iBotPeaches/Apktool

@Override
protected AbstractDirectory createDirLocal(String name) throws DirectoryException {
  File dir = new File(generatePath(name));
  dir.mkdir();
  return new FileDirectory(dir);
}

代码示例来源:origin: marytts/marytts

private void makeSureIsDirectory(File dir) throws IOException {
  if (!dir.isDirectory()) {
    boolean success;
    if (dir.exists()) { // exists, but is not a directory
      success = dir.delete();
      if (!success) {
        throw new IOException("Need to create directory " + dir.getPath()
            + ", but file exists that cannot be deleted.");
      }
    }
    success = dir.mkdir();
    if (!success) {
      throw new IOException("Cannot create directory " + dir.getPath());
    }
  }
}

代码示例来源:origin: iBotPeaches/Apktool

public static File createTempDirectory() throws BrutException {
  try {
    File tmp = File.createTempFile("BRUT", null);
    tmp.deleteOnExit();
    if (!tmp.delete()) {
      throw new BrutException("Could not delete tmp file: " + tmp.getAbsolutePath());
    }
    if (!tmp.mkdir()) {
      throw new BrutException("Could not create tmp dir: " + tmp.getAbsolutePath());
    }
    return tmp;
  } catch (IOException ex) {
    throw new BrutException("Could not create tmp dir", ex);
  }
}

代码示例来源:origin: apache/storm

private void makeArtifactoryCache(String location) throws IOException {
  // First make the cache dir
  String localDirName = ServerConfigUtils.masterLocalDir(conf) + File.separator + LOCAL_ARTIFACT_DIR;
  File dir = new File(localDirName);
  if (!dir.exists()) {
    dir.mkdirs();
  }
  localCacheDir = localDirName + File.separator + location.replaceAll(File.separator, "_");
  dir = new File(localCacheDir);
  if (!dir.exists()) {
    dir.mkdir();
  }
  cacheInitialized = true;
}

代码示例来源:origin: stackoverflow.com

File theDir = new File("new folder");

// if the directory does not exist, create it
if (!theDir.exists()) {
  System.out.println("creating directory: " + directoryName);
  boolean result = false;

  try{
    theDir.mkdir();
    result = true;
  } 
  catch(SecurityException se){
    //handle it
  }        
  if(result) {    
    System.out.println("DIR created");  
  }
}

相关文章

微信公众号

最新文章

更多