本文整理匯總了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));
}
示例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));
}
示例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);
}
示例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);
}
}
示例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);
}
示例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);
}
}
示例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);
}
示例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;
}
示例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();
}
示例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));
}
示例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);
}
}
示例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);
}
示例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);
}
}
}
示例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);
}
示例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();
}