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

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

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

File.deleteOnExit介绍

[英]Schedules this file to be automatically deleted when the VM terminates normally.

Note that on Android, the application lifecycle does not include VM termination, so calling this method will not ensure that files are deleted. Instead, you should use the most appropriate out of:

  • Use a finally clause to manually invoke #delete.
  • Maintain your own set of files to delete, and process it at an appropriate point in your application's lifecycle.
  • Use the Unix trick of deleting the file as soon as all readers and writers have opened it. No new readers/writers will be able to access the file, but all existing ones will still have access until the last one closes the file.
    [中]计划在VM正常终止时自动删除此文件。
    请注意,在Android上,应用程序生命周期不包括VM终止,因此调用此方法不会确保删除文件。相反,您应该使用以下最合适的选项:
    *使用finally子句手动调用#delete。
    *维护您自己要删除的文件集,并在应用程序生命周期中的适当时间对其进行处理。
    *使用Unix技巧,在所有读写器打开文件后立即将其删除。新的读写器将无法访问该文件,但在最后一个读写器关闭该文件之前,所有现有的读写器仍将具有访问权限。

代码示例

代码示例来源:origin: commons-io/commons-io

/**
 * Creates the lock file.
 *
 * @throws IOException if we cannot create the file
 */
private void createLock() throws IOException {
  synchronized (LockableFileWriter.class) {
    if (!lockFile.createNewFile()) {
      throw new IOException("Can't write file, lock " +
          lockFile.getAbsolutePath() + " exists");
    }
    lockFile.deleteOnExit();
  }
}

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

public static File createTestFile(File testFolder, String path) throws Exception {
  File subfile = new File(testFolder, path);
  subfile.createNewFile();
  subfile.deleteOnExit();
  return subfile;
}

代码示例来源:origin: skylot/jadx

public static File createTempFile(String suffix) {
  File temp;
  try {
    temp = File.createTempFile("jadx-tmp-", System.nanoTime() + "-" + suffix);
    temp.deleteOnExit();
  } catch (IOException e) {
    throw new JadxRuntimeException("Failed to create temp file with suffix: " + suffix);
  }
  return temp;
}

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

private static File copyResourceToFile(String resourcePath) throws IOException {
 if (tempDir == null){
  File tempFile = File.createTempFile("prefix", "suffix");
  tempFile.deleteOnExit();
  tempDir = tempFile.getParentFile();
 }
 InputStream jarIn = SdkStore.class.getClassLoader().getResourceAsStream(resourcePath);
 File outFile = new File(tempDir, new File(resourcePath).getName());
 outFile.deleteOnExit();
 try (FileOutputStream jarOut = new FileOutputStream(outFile)) {
  byte[] buffer = new byte[4096];
  int len;
  while ((len = jarIn.read(buffer)) != -1) {
   jarOut.write(buffer, 0, len);
  }
 }
 return outFile;
}

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

private static File createFileInTmp(String prefix, String suffix,
  String reason, boolean isDirectory) throws IOException {
 File file = File.createTempFile(prefix, suffix);
 if (isDirectory && (!file.delete() || !file.mkdirs())) {
  // TODO: or we could just generate a name ourselves and not do this?
  throw new IOException("Cannot recreate " + file + " as directory");
 }
 file.deleteOnExit();
 LOG.info(reason + "; created a tmp file: " + file.getAbsolutePath());
 return file;
}

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

public static File tmpDir() throws IOException {
  String tmpDirStr = System.getProperty(TmpDirTestCase.TEST_TMP_SYSTEM_PROPERTY_NAME);
  tmpDirStr = (tmpDirStr == null)? TmpDirTestCase.DEFAULT_TEST_TMP_DIR: tmpDirStr;
  File tmpDir = new File(tmpDirStr);
  FileUtils.ensureWriteableDirectory(tmpDir);
  if (!tmpDir.canWrite())
  {
    throw new IOException(tmpDir.getAbsolutePath() +
       " is unwriteable.");
  }
  tmpDir.deleteOnExit();
  return tmpDir;
}

代码示例来源:origin: jenkinsci/jenkins

File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());
if (tmp.exists()) {
  Util.deleteRecursive(tmp);
if(tmp.exists())
  tmp.deleteOnExit();

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

public static boolean assembleSmaliFile(InputStream is,DexBuilder dexBuilder, boolean verboseErrors,
                    boolean printTokens, File smaliFile) throws IOException, RecognitionException {
  // copy our filestream into a tmp file, so we don't overwrite
  File tmp = File.createTempFile("BRUT",".bak");
  tmp.deleteOnExit();
  OutputStream os = new FileOutputStream(tmp);
  IOUtils.copy(is, os);
  os.close();
  return assembleSmaliFile(tmp,dexBuilder, verboseErrors, printTokens);
}

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

@Test(groups = {LDAP, LDAP_CLI, PROFILE_SPECIFIC_TESTS}, timeOut = TIMEOUT)
public void shouldRunQueryFromFileWithLdap()
    throws IOException
{
  File temporayFile = File.createTempFile("test-sql", null);
  temporayFile.deleteOnExit();
  Files.write("select * from hive.default.nation;\n", temporayFile, UTF_8);
  launchPrestoCliWithServerArgument("--file", temporayFile.getAbsolutePath());
  assertThat(trimLines(presto.readRemainingOutputLines())).containsAll(nationTableBatchLines);
}

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

public void doLoad() {
 if (loaded) {
  return;
 }
 final long startTime = System.currentTimeMillis();
 File tempDir = Files.createTempDir();
 tempDir.deleteOnExit();
 File extractedLibraryPath = new File(tempDir, getLibName());
 try (FileOutputStream outputStream = new FileOutputStream(extractedLibraryPath)) {
  getLibraryByteSource().copyTo(outputStream);
 } catch (IOException e) {
  throw new RuntimeException("Cannot extract SQLite library into " + extractedLibraryPath, e);
 }
 loadFromDirectory(tempDir);
 logWithTime("SQLite natives prepared in", startTime);
}

代码示例来源:origin: AsyncHttpClient/async-http-client

public static File resourceAsFile(String path) throws URISyntaxException, IOException {
 ClassLoader cl = TestUtils.class.getClassLoader();
 URI uri = cl.getResource(path).toURI();
 if (uri.isAbsolute() && !uri.isOpaque()) {
  return new File(uri);
 } else {
  File tmpFile = File.createTempFile("tmpfile-", ".data", TMP_DIR);
  tmpFile.deleteOnExit();
  try (InputStream is = cl.getResourceAsStream(path)) {
   FileUtils.copyInputStreamToFile(is, tmpFile);
   return tmpFile;
  }
 }
}

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

private void setupOutputFileStreams() throws IOException {
 parentDir = FileUtils.createLocalDirsTempFile(spillLocalDirs, "bytes-container", "", true);
 parentDir.deleteOnExit();
 tmpFile = File.createTempFile("BytesContainer", ".tmp", parentDir);
 LOG.debug("BytesContainer created temp file " + tmpFile.getAbsolutePath());
 tmpFile.deleteOnExit();
 fileOutputStream = new FileOutputStream(tmpFile);
}

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

/**
 * {@inheritDoc}
 */
public File inject(File jar) throws IOException {
  File temporary = doInject(jar, File.createTempFile(jar.getName(), TEMP_SUFFIX));
  boolean delete = true;
  try {
    delete = DISPATCHER.copy(temporary, jar);
  } finally {
    if (delete && !temporary.delete()) {
      temporary.deleteOnExit();
    }
  }
  return jar;
}

代码示例来源:origin: spring-projects/spring-framework

static void createGzippedFile(String filePath) throws IOException {
  Resource location = new ClassPathResource("test/", EncodedResourceResolverTests.class);
  Resource resource = new FileSystemResource(location.createRelative(filePath).getFile());
  Path gzFilePath = Paths.get(resource.getFile().getAbsolutePath() + ".gz");
  Files.deleteIfExists(gzFilePath);
  File gzFile = Files.createFile(gzFilePath).toFile();
  GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFile));
  FileCopyUtils.copy(resource.getInputStream(), out);
  gzFile.deleteOnExit();
}

代码示例来源:origin: Tencent/tinker

public static final boolean safeDeleteFile(File file) {
  if (file == null) {
    return true;
  }
  if (file.exists()) {
    Log.i(TAG, "safeDeleteFile, try to delete path: " + file.getPath());
    boolean deleted = file.delete();
    if (!deleted) {
      Log.e(TAG, "Failed to delete file, try to delete when exit. path: " + file.getPath());
      file.deleteOnExit();
    }
    return deleted;
  }
  return true;
}

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

private boolean delete(File file) {
  boolean deleted = file.delete();
  if (!deleted) {
    file.deleteOnExit();
    logError("Could not delete " + file.getAbsolutePath());
  }
  return deleted;
}

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

private void createTempFiles(byte[] contents, File... files) throws IOException {
  for (File child : files) {
    child.deleteOnExit();
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(child));
    try {
      out.write(contents);
    } finally {
      out.close();
    }
  }
}

代码示例来源:origin: commons-codec/commons-codec

@After
public void tearDown() {
  if (!testFile.delete()) {
    testFile.deleteOnExit();
  }
}

代码示例来源:origin: apache/incubator-gobblin

/**
  * Get ivy settings file from classpath
  */
 public static File getIvySettingsFile() throws IOException {
  URL settingsUrl = Thread.currentThread().getContextClassLoader().getResource(IVY_SETTINGS_FILE_NAME);
  if (settingsUrl == null) {
   throw new IOException("Failed to find " + IVY_SETTINGS_FILE_NAME + " from class path");
  }

  // Check if settingsUrl is file on classpath
  File ivySettingsFile = new File(settingsUrl.getFile());
  if (ivySettingsFile.exists()) {
   // can access settingsUrl as a file
   return ivySettingsFile;
  }

  // Create temporary Ivy settings file.
  ivySettingsFile = File.createTempFile("ivy.settings", ".xml");
  ivySettingsFile.deleteOnExit();

  try (OutputStream os = new BufferedOutputStream(new FileOutputStream(ivySettingsFile))) {
   Resources.copy(settingsUrl, os);
  }

  return ivySettingsFile;
 }
}

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

public List<ScoredObject<Tree>> getKBestParses(List<? extends HasWord> sentence, int k, boolean deleteTempFiles) {
 try {
  File inFile = File.createTempFile("charniak.", ".in");
  if (deleteTempFiles) inFile.deleteOnExit();
  File outFile = File.createTempFile("charniak.", ".out");
  if (deleteTempFiles) outFile.deleteOnExit();
  File errFile = File.createTempFile("charniak.", ".err");
  if (deleteTempFiles) errFile.deleteOnExit();
  printSentence(sentence, inFile.getAbsolutePath());
  runCharniak(k, inFile.getAbsolutePath(), outFile.getAbsolutePath(), errFile.getAbsolutePath());
  Iterable<List<ScoredObject<Tree>>> iter = CharniakScoredParsesReaderWriter.readScoredTrees(outFile.getAbsolutePath());
  if (deleteTempFiles) {
   inFile.delete();
   outFile.delete();
   errFile.delete();
  }
  return iter.iterator().next();
 } catch (IOException ex) {
  throw new RuntimeException(ex);
 }
}

相关文章