当前位置: 首页>>代码示例>>Java>>正文


Java Files.createTempFile方法代码示例

本文整理汇总了Java中java.nio.file.Files.createTempFile方法的典型用法代码示例。如果您正苦于以下问题:Java Files.createTempFile方法的具体用法?Java Files.createTempFile怎么用?Java Files.createTempFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.file.Files的用法示例。


在下文中一共展示了Files.createTempFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import java.nio.file.Files; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
    // create a zip file, and read it in as a byte array
    Path path = Files.createTempFile("bad", ".zip");
    try (OutputStream os = Files.newOutputStream(path);
            ZipOutputStream zos = new ZipOutputStream(os)) {
        ZipEntry e = new ZipEntry("x");
        zos.putNextEntry(e);
        zos.write((int) 'x');
    }
    int len = (int) Files.size(path);
    byte[] data = new byte[len];
    try (InputStream is = Files.newInputStream(path)) {
        is.read(data);
    }
    Files.delete(path);

    // year, month, day are zero
    testDate(data.clone(), 0, LocalDate.of(1979, 11, 30));
    // only year is zero
    testDate(data.clone(), 0 << 25 | 4 << 21 | 5 << 16, LocalDate.of(1980, 4, 5));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:ZeroDate.java

示例2: end2endStaging

import java.nio.file.Files; //导入方法依赖的package包/类
@Test
public void end2endStaging() throws Exception {
  List<StagedPackage> stagedPackages =
      StagingUtil.stageClasspathElements(testFiles, stagingLocation);

  RunManifest manifest = new RunManifestBuilder()
      .continuation(stagedPackages.get(0).name())
      .files(stagedPackages.stream().map(StagedPackage::name).collect(toList()))
      .build();

  Path manifestFile = stagingPath.resolve("manifest.txt");
  RunManifest.write(manifest, manifestFile);

  // add one extra file to staging directory
  Files.createTempFile(stagingPath, "extra", "");
  List<Path> stagedFiles = Files.list(stagingPath).collect(toList());
  assertThat(stagedFiles.size(), is(testFiles.size() + 2)); // extra + manifest

  Path readPath = Files.createTempDirectory("unit-test");
  RunManifest downloadedManifest = ManifestLoader.downloadManifest(manifestFile, readPath);

  List<Path> readFiles = Files.list(readPath).collect(toList());
  assertThat(readFiles.size(), is(testFiles.size()));
  assertThat(downloadedManifest, is(manifest));
}
 
开发者ID:spotify,项目名称:hype,代码行数:26,代码来源:ManifestLoaderTest.java

示例3: main

import java.nio.file.Files; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
  FluentLogger logger = FluentLogger.forEnclosingClass();
  SimulatorDeviceHost simHost = SimulatorDeviceHost.INSTANCE;

  // Optionally shutdown all devices before starting one.
  simHost.shutdownAllDevices();

  // Pick an arbitrary device.
  SimulatorDevice sim = (SimulatorDevice) simHost.connectedDevices().iterator().next();
  // Or specify one by udid
  // SimulatorDevice sim = (SimulatorDevice) simHost.connectedDevice(udid);

  // Start the device before interacting with it.
  sim.startup();

  // The device can now be interacted with. Here is an example of starting Safari, taking a
  // screenshot, then closing Safari
  IosAppProcess safariProcess = sim.runApplication(new IosAppBundleId("com.apple.mobilesafari"));
  byte[] screenshotBytes = sim.takeScreenshot();
  Path screenshotPath = Files.createTempFile("screenshot", ".png");
  Files.write(screenshotPath, screenshotBytes);
  safariProcess.kill();
  logger.atInfo().log("Screenshot written to: %s", screenshotPath);
}
 
开发者ID:google,项目名称:ios-device-control,代码行数:25,代码来源:ExampleSimulatorDeviceControl.java

示例4: testDate

import java.nio.file.Files; //导入方法依赖的package包/类
private static void testDate(byte[] data, int date, LocalDate expected) throws IOException {
    // set the datetime
    int endpos = data.length - ENDHDR;
    int cenpos = u16(data, endpos + ENDOFF);
    int locpos = u16(data, cenpos + CENOFF);
    writeU32(data, cenpos + CENTIM, date);
    writeU32(data, locpos + LOCTIM, date);

    // ensure that the archive is still readable, and the date is 1979-11-30
    Path path = Files.createTempFile("out", ".zip");
    try (OutputStream os = Files.newOutputStream(path)) {
        os.write(data);
    }
    try (ZipFile zf = new ZipFile(path.toFile())) {
        ZipEntry ze = zf.entries().nextElement();
        Instant actualInstant = ze.getLastModifiedTime().toInstant();
        Instant expectedInstant =
                expected.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        if (!actualInstant.equals(expectedInstant)) {
            throw new AssertionError(
                    String.format("actual: %s, expected: %s", actualInstant, expectedInstant));
        }
    } finally {
        Files.delete(path);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:27,代码来源:ZeroDate.java

示例5: expunge

import java.nio.file.Files; //导入方法依赖的package包/类
private static void expunge(Path p, KerberosTime currTime)
        throws IOException {
    Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
    try (SeekableByteChannel oldChan = Files.newByteChannel(p);
            SeekableByteChannel newChan = createNoClose(p2)) {
        long timeLimit = currTime.getSeconds() - readHeader(oldChan);
        while (true) {
            try {
                AuthTime at = AuthTime.readFrom(oldChan);
                if (at.ctime > timeLimit) {
                    ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
                    newChan.write(bb);
                }
            } catch (BufferUnderflowException e) {
                break;
            }
        }
    }
    makeMine(p2);
    Files.move(p2, p,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:24,代码来源:DflCache.java

示例6: update

import java.nio.file.Files; //导入方法依赖的package包/类
@Override
public void update(Session session) {
    final String sessionId = ensureStringSessionId(session);
    final Path oldPath = sessionId2Path(sessionId);
    if (!Files.exists(oldPath)) {
        throw new UnknownSessionException(sessionId);
    }

    try {
        final Path newPath = Files.createTempFile(tmpDir, null, null);
        Files.write(newPath, serialize(session));
        Files.move(newPath, oldPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new SerializationException(e);
    }
}
 
开发者ID:line,项目名称:centraldogma,代码行数:17,代码来源:FileBasedSessionDAO.java

示例7: rxJournalClearsOnlyCq4FilesAndKeepsBaseDir

import java.nio.file.Files; //导入方法依赖的package包/类
@Test
public void rxJournalClearsOnlyCq4FilesAndKeepsBaseDir() throws IOException {
    Files.createDirectories(expectedDir);
    Path tempFile = Files.createTempFile(expectedDir, "rxJournalClearsOnlyCq4", ".txt");

    ReactiveJournal journal = new ReactiveJournal(base.toString());

    ReactiveRecorder recorder = journal.createReactiveRecorder();
    recorder.record(Flowable.just("foo"), "");

    //short circuit the test if the dir is unexpected, just in case the clearCache would then be too destructive
    Assert.assertEquals(expectedDir.toString(), journal.getDir());

    journal.clearCache();

    Assert.assertTrue(Files.exists(expectedDir));
    Assert.assertTrue(Files.exists(tempFile));

    long count = Files.walk(expectedDir, 1)
            .map(Path::toFile)
            .filter(File::isFile)
            .count();

    Assert.assertEquals(1, count);
}
 
开发者ID:danielshaya,项目名称:reactivejournal,代码行数:26,代码来源:ReactiveJournalDirectoryTest.java

示例8: buildAgent

import java.nio.file.Files; //导入方法依赖的package包/类
private static Path buildAgent() throws IOException {
    Path manifest = TestLambdaFormRetransformation.createManifest();
    Path jar = Files.createTempFile(Paths.get("."), null, ".jar");

    String[] args = new String[] {
        "-cfm",
        jar.toAbsolutePath().toString(),
        manifest.toAbsolutePath().toString(),
        "-C",
        TestLambdaFormRetransformation.CP,
        Agent.class.getName() + ".class"
    };

    sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar");

    if (!jarTool.run(args)) {
        throw new Error("jar failed: args=" + Arrays.toString(args));
    }
    return jar;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:21,代码来源:TestLambdaFormRetransformation.java

示例9: createTempFile

import java.nio.file.Files; //导入方法依赖的package包/类
static private
File createTempFile(String basefile, String suffix) throws IOException {
    File base = new File(basefile);
    String prefix = base.getName();
    if (prefix.length() < 3)  prefix += "tmp";

    File where = (base.getParentFile() == null && suffix.equals(".bak"))
            ? new File(".").getAbsoluteFile()
            : base.getParentFile();

    Path tmpfile = (where == null)
            ? Files.createTempFile(prefix, suffix)
            : Files.createTempFile(where.toPath(), prefix, suffix);

    return tmpfile.toFile();
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:17,代码来源:Driver.java

示例10: writeManifest

import java.nio.file.Files; //导入方法依赖的package包/类
@Test
public void writeManifest() throws Exception {
  Path manifest = Files.createTempFile("manifest", ".txt");
  ManifestUtil.write(EXAMPLE, manifest);

  List<String> expected = Files.readAllLines(load("/example-manifest.txt"));
  List<String> strings = Files.readAllLines(manifest);

  assertThat(strings, is(expected));
}
 
开发者ID:spotify,项目名称:hype,代码行数:11,代码来源:ManifestUtilTest.java

示例11: newTempFile

import java.nio.file.Files; //导入方法依赖的package包/类
private Path newTempFile() {
  try {
    return Files.createTempFile(tmpDirInCacheDir, null, null);
  } catch (IOException e) {
    throw new IllegalStateException("Fail to create temp file in " + tmpDirInCacheDir, e);
  }
}
 
开发者ID:instalint-org,项目名称:instalint,代码行数:8,代码来源:PluginCache.java

示例12: before

import java.nio.file.Files; //导入方法依赖的package包/类
@BeforeClass
public void before() throws Exception {
    Path root = Files.createTempFile("stargraph-", "-dataDir");
    Path hdtPath = createPath(root, factsId).resolve("triples.hdt");
    copyResource("dataSets/obama/facts/triples.hdt", hdtPath);
    System.setProperty("stargraph.data.root-dir", root.toString());
    ConfigFactory.invalidateCaches();
    stargraph = new Stargraph();

    //TODO: replace with KBLoader#loadAll()
    loadProperties(stargraph);
    loadEntities(stargraph);
    loadFacts(stargraph);
}
 
开发者ID:Lambda-3,项目名称:Stargraph,代码行数:15,代码来源:ElasticIndexerIT.java

示例13: macImpl

import java.nio.file.Files; //导入方法依赖的package包/类
/** try to install our custom rule profile into sandbox_init() to block execution */
private static void macImpl(Path tmpFile) throws IOException {
    // first be defensive: we can give nice errors this way, at the very least.
    boolean supported = Constants.MAC_OS_X;
    if (supported == false) {
        throw new IllegalStateException("bug: should not be trying to initialize seatbelt for an unsupported OS");
    }

    // we couldn't link methods, could be some really ancient OS X (< Leopard) or some bug
    if (libc_mac == null) {
        throw new UnsupportedOperationException("seatbelt unavailable: could not link methods. requires Leopard or above.");
    }

    // write rules to a temporary file, which will be passed to sandbox_init()
    Path rules = Files.createTempFile(tmpFile, "es", "sb");
    Files.write(rules, Collections.singleton(SANDBOX_RULES));

    boolean success = false;
    try {
        PointerByReference errorRef = new PointerByReference();
        int ret = libc_mac.sandbox_init(rules.toAbsolutePath().toString(), SANDBOX_NAMED, errorRef);
        // if sandbox_init() fails, add the message from the OS (e.g. syntax error) and free the buffer
        if (ret != 0) {
            Pointer errorBuf = errorRef.getValue();
            RuntimeException e = new UnsupportedOperationException("sandbox_init(): " + errorBuf.getString(0));
            libc_mac.sandbox_free_error(errorBuf);
            throw e;
        }
        logger.debug("OS X seatbelt initialization successful");
        success = true;
    } finally {
        if (success) {
            Files.delete(rules);
        } else {
            IOUtils.deleteFilesIgnoringExceptions(rules);
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:39,代码来源:SystemCallFilter.java

示例14: verifyFileContentEquality

import java.nio.file.Files; //导入方法依赖的package包/类
protected void verifyFileContentEquality() throws IOException {
    final Path tmp = Files.createTempFile("tmp", "" + key.hashCode());
    defaultAmazonS3().getObject(new GetObjectRequest(testBucket, key), tmp.toFile());

    assertArrayEquals(Files.readAllBytes(file.path), Files.readAllBytes(tmp));

    Files.delete(tmp);
}
 
开发者ID:mentegy,项目名称:s3-channels,代码行数:9,代码来源:AbstractS3WritableObjectChannelSuite.java

示例15: FileBucket

import java.nio.file.Files; //导入方法依赖的package包/类
public FileBucket() {
    try {
        path = Files.createTempFile(null, null);
        Files.deleteIfExists(path);
        Files.createFile(path);
    } catch (IOException e) {
        ExceptionHandler.log(e);
    }
    path.toFile().deleteOnExit();
}
 
开发者ID:avedensky,项目名称:JavaRushTasks,代码行数:11,代码来源:FileBucket.java


注:本文中的java.nio.file.Files.createTempFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。