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

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

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

File.createTempFile介绍

[英]Creates an empty temporary file using the given prefix and suffix as part of the file name. If suffix is null, .tmp is used. This method is a convenience method that calls #createTempFile(String,String,File) with the third argument being null.
[中]使用给定的前缀和后缀作为文件名的一部分创建空临时文件。如果后缀为空。使用tmp。此方法是一种方便的方法,它调用#createTempFile(String,String,File),第三个参数为null。

代码示例

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

public File createSegmentDescriptorFile(final ObjectMapper jsonMapper, final DataSegment segment) throws
                                                 IOException
{
 File descriptorFile = File.createTempFile("descriptor", ".json");
 try (FileOutputStream stream = new FileOutputStream(descriptorFile)) {
  stream.write(jsonMapper.writeValueAsBytes(segment));
 }
 return descriptorFile;
}

代码示例来源: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: libgdx/libgdx

static public FileDescriptor tempDirectory (String prefix) {
  try {
    File file = File.createTempFile(prefix, null);
    if (!file.delete()) throw new IOException("Unable to delete temp file: " + file);
    if (!file.mkdir()) throw new IOException("Unable to create temp directory: " + file);
    return new FileDescriptor(file);
  } catch (IOException ex) {
    throw new RuntimeException("Unable to create temp file.", ex);
  }
}

代码示例来源: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: junit-team/junit4

private File createTemporaryFolderIn(File parentFolder) throws IOException {
  File createdFolder = null;
  for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) {
    // Use createTempFile to get a suitable folder name.
    String suffix = ".tmp";
    File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder);
    String tmpName = tmpFile.toString();
    // Discard .tmp suffix of tmpName.
    String folderName = tmpName.substring(0, tmpName.length() - suffix.length());
    createdFolder = new File(folderName);
    if (createdFolder.mkdir()) {
      tmpFile.delete();
      return createdFolder;
    }
    tmpFile.delete();
  }
  throw new IOException("Unable to create temporary directory in: "
    + parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. "
    + "Last attempted to create: " + createdFolder.toString());
}

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

@Override
  public String invoke(File dir, VirtualChannel channel) throws IOException {
    if(!inThisDirectory)
      dir = new File(System.getProperty("java.io.tmpdir"));
    else
      mkdirs(dir);
    File f;
    try {
      f = creating(File.createTempFile(prefix, suffix, dir));
    } catch (IOException e) {
      throw new IOException("Failed to create a temporary directory in "+dir,e);
    }
    try (Writer w = new FileWriter(writing(f))) {
      w.write(contents);
    }
    return f.getAbsolutePath();
  }
}

代码示例来源: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: SonarSource/sonarqube

void checkWritableDir(String tempPath) {
 try {
  File tempFile = File.createTempFile("check", "tmp", new File(tempPath));
  deleteQuietly(tempFile);
 } catch (IOException e) {
  throw new IllegalStateException(format("Temp directory is not writable: %s", tempPath), e);
 }
}

代码示例来源: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: skylot/jadx

public void test() throws IOException {
    File file = File.createTempFile("test", "txt");
    OutputStream outputStream = new FileOutputStream(file);
    try {
      outputStream.write(1);
    } finally {
      try {
        outputStream.close();
        file.delete();
      } catch (IOException e) {
      }
    }
  }
}

代码示例来源: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: commons-io/commons-io

/**
 * Switches the underlying output stream from a memory based stream to one
 * that is backed by disk. This is the point at which we realise that too
 * much data is being written to keep in memory, so we elect to switch to
 * disk-based storage.
 *
 * @throws IOException if an error occurs.
 */
@Override
protected void thresholdReached() throws IOException
{
  if (prefix != null) {
    outputFile = File.createTempFile(prefix, suffix, directory);
  }
  FileUtils.forceMkdirParent(outputFile);
  final FileOutputStream fos = new FileOutputStream(outputFile);
  try {
    memoryOutputStream.writeTo(fos);
  } catch (final IOException e){
    fos.close();
    throw e;
  }
  currentOutputStream = fos;
  memoryOutputStream = null;
}

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

@Before
public void createFile() throws Exception {
  path = File.createTempFile("csv_output_test_file", ".csv").getAbsolutePath();
}

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

private File createTempDir(String prefix) {
  try {
    File tempFolder = File.createTempFile(prefix + ".", "." + getPort());
    tempFolder.delete();
    tempFolder.mkdir();
    tempFolder.deleteOnExit();
    return tempFolder;
  }
  catch (IOException ex) {
    throw new IllegalStateException("Unable to create temp directory", ex);
  }
}

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

/**
 * Creates a temporary directory whose name will start by prefix
 *
 * <p>Strategy is to leverage the system temp directory, then create a sub-directory.
 */
public static File createTempDirectory(String prefix) throws IOException {
  File dummyTemp = File.createTempFile("blah", null);
  String sysTempDir = dummyTemp.getParentFile().getAbsolutePath();
  dummyTemp.delete();
  File reqTempDir = new File(sysTempDir + File.separator + prefix + Math.random());
  reqTempDir.mkdir();
  return reqTempDir;
}

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

/** Returns a path to a file that can be written. Tries multiple locations and verifies writing succeeds.
 * @return null if a writable path could not be found. */
private File getExtractedFile (String dirName, String fileName) {
  // Temp directory with username in path.
  File idealFile = new File(
    System.getProperty("java.io.tmpdir") + "/libgdx" + System.getProperty("user.name") + "/" + dirName, fileName);
  if (canWrite(idealFile)) return idealFile;
  // System provided temp directory.
  try {
    File file = File.createTempFile(dirName, null);
    if (file.delete()) {
      file = new File(file, fileName);
      if (canWrite(file)) return file;
    }
  } catch (IOException ignored) {
  }
  // User home.
  File file = new File(System.getProperty("user.home") + "/.libgdx/" + dirName, fileName);
  if (canWrite(file)) return file;
  // Relative directory.
  file = new File(".temp/" + dirName, fileName);
  if (canWrite(file)) return file;
  // We are running in the OS X sandbox.
  if (System.getenv("APP_SANDBOX_CONTAINER_ID") != null) return idealFile;
  return null;
}

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

@Test
 public void simpleDirectoryTest() throws IOException, SegmentLoadingException
 {
  File srcDir = temporaryFolder.newFolder();
  File tmpFile = File.createTempFile("test", "file", srcDir);
  File expectedOutput = new File(tmpDir, Files.getNameWithoutExtension(tmpFile.getAbsolutePath()));
  Assert.assertFalse(expectedOutput.exists());
  puller.getSegmentFiles(srcDir, tmpDir);
  Assert.assertTrue(expectedOutput.exists());
 }
}

代码示例来源:origin: google/guava

/**
  * Checks if writing {@code len} bytes would go over threshold, and switches to file buffering if
  * so.
  */
 private void update(int len) throws IOException {
  if (file == null && (memory.getCount() + len > fileThreshold)) {
   File temp = File.createTempFile("FileBackedOutputStream", null);
   if (resetOnFinalize) {
    // Finalizers are not guaranteed to be called on system shutdown;
    // this is insurance.
    temp.deleteOnExit();
   }
   FileOutputStream transfer = new FileOutputStream(temp);
   transfer.write(memory.getBuffer(), 0, memory.getCount());
   transfer.flush();

   // We've successfully transferred the data; switch to writing to file
   out = transfer;
   file = temp;
   memory = null;
  }
 }
}

代码示例来源:origin: hankcs/HanLP

public void train(String trainFile, String modelFile,
         int maxitr, int freq, double eta, double C, int threadNum, int shrinkingSize,
         Encoder.Algorithm algorithm) throws IOException
{
  String templFile = null;
  File tmpTemplate = File.createTempFile("crfpp-template-" + new Date().getTime(), ".txt");
  tmpTemplate.deleteOnExit();
  templFile = tmpTemplate.getAbsolutePath();
  String template = getDefaultFeatureTemplate();
  IOUtil.saveTxt(templFile, template);
  File tmpTrain = File.createTempFile("crfpp-train-" + new Date().getTime(), ".txt");
  tmpTrain.deleteOnExit();
  convertCorpus(trainFile, tmpTrain.getAbsolutePath());
  trainFile = tmpTrain.getAbsolutePath();
  System.out.printf("Java效率低,建议安装CRF++,执行下列等价训练命令(不要终止本进程,否则临时语料库和特征模板将被清除):\n" +
             "crf_learn -m %d -f %d -e %f -c %f -p %d -H %d -a %s -t %s %s %s\n", maxitr, freq, eta,
           C, threadNum, shrinkingSize, algorithm.toString().replace('_', '-'),
           templFile, trainFile, modelFile);
  Encoder encoder = new Encoder();
  if (!encoder.learn(templFile, trainFile, modelFile,
            true, maxitr, freq, eta, C, threadNum, shrinkingSize, algorithm))
  {
    throw new IOException("fail to learn model");
  }
  convert(modelFile);
}

相关文章