Example usage for java.nio.file Files createTempFile

List of usage examples for java.nio.file Files createTempFile

Introduction

In this page you can find the example usage for java.nio.file Files createTempFile.

Prototype

public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException 

Source Link

Document

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Usage

From source file:org.apache.beam.sdk.io.TextIOTest.java

License:asdf

private <T> void runTestRead(String[] expected) throws Exception {
    File tmpFile = Files.createTempFile(tempFolder, "file", "txt").toFile();
    String filename = tmpFile.getPath();

    try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) {
        for (String elem : expected) {
            byte[] encodedElem = CoderUtils.encodeToByteArray(StringUtf8Coder.of(), elem);
            String line = new String(encodedElem);
            writer.println(line);/* ww w  .  java  2 s . co m*/
        }
    }

    TextIO.Read read = TextIO.read().from(filename);

    PCollection<String> output = p.apply(read);

    PAssert.that(output).containsInAnyOrder(expected);
    p.run();
}

From source file:business.services.FileService.java

public File clone(File file) {
    try {//from  www .j a  va  2  s  .  c  om
        FileSystem fileSystem = FileSystems.getDefault();
        // source
        Path source = fileSystem.getPath(uploadPath, file.getFilename());
        // target
        Path path = fileSystem.getPath(uploadPath).normalize();
        String prefix = getBasename(file.getFilename());
        String suffix = getExtension(file.getFilename());
        Path target = Files.createTempFile(path, prefix, suffix).normalize();
        // copy
        log.info("Copying " + source + " to " + target + " ...");
        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
        // save clone
        File result = file.clone();
        result.setFilename(target.getFileName().toString());
        return save(result);
    } catch (IOException e) {
        log.error(e);
        throw new FileCopyError();
    }
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromFolder(String path) {
    try {//from  www  .j a va2  s.  c o m
        final Path root = Paths.get(path);
        final Path dockerIgnore = root.resolve(DOCKER_IGNORE);
        final List<String> ignorePatterns = new ArrayList<>();
        if (dockerIgnore.toFile().exists()) {
            for (String p : Files.readAllLines(dockerIgnore, UTF_8)) {
                ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p);
            }
        }

        final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns);

        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();

        try (FileOutputStream fout = new FileOutputStream(tempFile);
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout);
                final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) {
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (dockerIgnorePathMatcher.matches(dir)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (dockerIgnorePathMatcher.matches(file)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    final Path relativePath = root.relativize(file);
                    final TarArchiveEntry entry = new TarArchiveEntry(file.toFile());
                    entry.setName(relativePath.toString());
                    entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);
                    entry.setSize(attrs.size());
                    tout.putArchiveEntry(entry);
                    Files.copy(file, tout);
                    tout.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
            fout.flush();
        }
        return fromTar(tempFile.getAbsolutePath());

    } catch (IOException e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:searcher.FileScanRunnable.java

private void initStream() {
    if (outputSeparateFile != null) {
        try {/*from   www  .ja  v a  2s.c o m*/
            Files.createDirectories(outputSeparateFile.getDirectoryPathResult());
            Path file = Files.createTempFile(outputSeparateFile.getDirectoryPathResult(),
                    outputSeparateFile.getPrefix() + "_",
                    "_" + fileRootSearch.getPath().getFileName().toString() + ".txt");
            out = new PrintWriter(new BufferedWriter(new FileWriter(file.toFile(), false)));
            separateFile = true;
            LOGGER.info("il risultato della ricerca nel file = "
                    + fileRootSearch.getPath().toAbsolutePath().toString() + " verra' scritto nel file = "
                    + file.toAbsolutePath().toString());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
    if (out == null) {
        out = new PrintWriter(new BufferedOutputStream(System.out));
    }
}

From source file:com.google.cloud.dataflow.sdk.io.TextIOTest.java

License:asdf

private <T> void runTestRead(T[] expected, Coder<T> coder) throws Exception {
    File tmpFile = Files.createTempFile(tempFolder, "file", "txt").toFile();
    String filename = tmpFile.getPath();

    try (PrintStream writer = new PrintStream(new FileOutputStream(tmpFile))) {
        for (T elem : expected) {
            byte[] encodedElem = CoderUtils.encodeToByteArray(coder, elem);
            String line = new String(encodedElem);
            writer.println(line);/*  w ww. j a  v  a  2s  . c om*/
        }
    }

    Pipeline p = TestPipeline.create();

    TextIO.Read.Bound<T> read;
    if (coder.equals(StringUtf8Coder.of())) {
        TextIO.Read.Bound<String> readStrings = TextIO.Read.from(filename);
        // T==String
        read = (TextIO.Read.Bound<T>) readStrings;
    } else {
        read = TextIO.Read.from(filename).withCoder(coder);
    }

    PCollection<T> output = p.apply(read);

    DataflowAssert.that(output).containsInAnyOrder(expected);
    p.run();
}

From source file:org.syncany.plugins.local.LocalTransferManager.java

@Override
public boolean testTargetCanWrite() {
    try {//www. j  a  v  a  2s. co m
        if (Files.isDirectory(repoPath)) {
            Path tempFile = Files.createTempFile(repoPath, "syncany-write-test", "tmp");
            Files.delete(tempFile);

            logger.log(Level.INFO, "testTargetCanWrite: Can write, test file created/deleted successfully.");
            return true;
        } else {
            logger.log(Level.INFO, "testTargetCanWrite: Can NOT write, target does not exist.");
            return false;
        }
    } catch (Exception e) {
        logger.log(Level.INFO, "testTargetCanWrite: Can NOT write to target.", e);
        return false;
    }
}

From source file:codes.thischwa.c5c.DispatcherPUT.java

private Path saveTemp(InputStream in, String name) throws IOException {
    String baseName = FilenameUtils.getBaseName(name);
    String ext = FilenameUtils.getExtension(name);
    try {/*from w  ww.j av  a2  s .  c  o  m*/
        Path tempPath = Files.createTempFile(UserObjectProxy.getTempDirectory(), baseName, "." + ext);
        Files.copy(in, tempPath, StandardCopyOption.REPLACE_EXISTING);
        return tempPath;
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:com.facebook.presto.hive.TestPrestoS3FileSystem.java

@Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Configured staging path is not a directory: .*")
public void testCreateWithStagingDirectoryFile() throws Exception {
    java.nio.file.Path tmpdir = Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value());
    java.nio.file.Path staging = Files.createTempFile(tmpdir, "staging", null);
    // staging = /tmp/stagingXXX.tmp

    try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) {
        MockAmazonS3 s3 = new MockAmazonS3();
        Configuration conf = new Configuration();
        conf.set(PrestoS3FileSystem.S3_STAGING_DIRECTORY, staging.toString());
        fs.initialize(new URI("s3n://test-bucket/"), conf);
        fs.setS3Client(s3);//from w w  w.java  2  s.c om
        fs.create(new Path("s3n://test-bucket/test"));
    } finally {
        Files.deleteIfExists(staging);
    }
}

From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java

public ProcessInfo _exec(Class<?> clazz, ServerType serverType, Map<String, String> configOverrides,
        String... args) throws IOException {
    List<String> jvmOpts = new ArrayList<>();
    jvmOpts.add("-Xmx" + config.getMemory(serverType));
    if (configOverrides != null && !configOverrides.isEmpty()) {
        File siteFile = Files.createTempFile(config.getConfDir().toPath(), "accumulo", ".properties").toFile();
        Map<String, String> confMap = new HashMap<>();
        confMap.putAll(config.getSiteConfig());
        confMap.putAll(configOverrides);
        writeConfigProperties(siteFile, confMap);
        jvmOpts.add("-Daccumulo.properties=" + siteFile.getName());
    }//from  w w w . j  a va  2s . com

    if (config.isJDWPEnabled()) {
        int port = PortUtils.getRandomFreePort();
        jvmOpts.addAll(buildRemoteDebugParams(port));
        debugPorts.add(new Pair<>(serverType, port));
    }
    return _exec(clazz, jvmOpts, args);
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromTar(InputStream is) {
    try {/* www .j  a v  a2  s.c o  m*/
        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();
        Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return fromTar(tempFile.getAbsolutePath());
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}