Example usage for java.io File createTempFile

List of usage examples for java.io File createTempFile

Introduction

In this page you can find the example usage for java.io File createTempFile.

Prototype

public static File createTempFile(String prefix, String suffix) 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:de.topobyte.largescalefileio.TestClosingFileOutputStream.java

public void test(int n, boolean existingFiles) throws IOException {
    files = new File[n];
    for (int i = 0; i < n; i++) {
        files[i] = File.createTempFile("closing-fos", ".dat");
    }//www  . j  a v  a2s .  co m
    allFiles.addAll(Arrays.asList(files));

    ByteArrayGenerator generator = new ByteArrayGenerator();
    byte[][] bytes = new byte[n][];
    for (int i = 0; i < n; i++) {
        bytes[i] = generator.generateBytes(1024);
    }

    if (existingFiles) {
        for (int i = 0; i < n; i++) {
            writeSomeData(files[i], generator);
        }
    }

    ClosingFileOutputStreamFactory factory = new SimpleClosingFileOutputStreamFactory();

    OutputStream[] outputs = new OutputStream[n];
    for (int i = 0; i < n; i++) {
        outputs[i] = factory.create(files[i]);
    }

    WriterUtil.writeInterleaved(outputs, bytes);

    for (int i = 0; i < n; i++) {
        outputs[i].close();
    }

    for (int i = 0; i < n; i++) {
        byte[] read = FileUtils.readFileToByteArray(files[i]);
        Assert.assertArrayEquals(bytes[i], read);
    }
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Ffmpeg.java

@Override
public Object handle(Task aTask) throws Exception {
    List<String> options = aTask.getList("options", String.class);
    CommandLine cmd = new CommandLine("ffmpeg");
    options.forEach(o -> cmd.addArgument(o));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        int exitValue = exec.execute(cmd);
        return exitValue != 0 ? FileUtils.readFileToString(tempFile) : cmd.toString();
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {//from  w ww . j a v  a2 s  .c o m
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:net.praqma.jenkins.unit.MemoryMapParserDelegateTest.java

@Test
public void findFilePatternWorks_test() throws IOException {

    File f = File.createTempFile("testfile", ".test");

    System.out.println(f.getAbsolutePath());

    MemoryMapMapParserDelegate delegate = new MemoryMapMapParserDelegate();

    TexasInstrumentsMemoryMapParser parser = new TexasInstrumentsMemoryMapParser("*.config", "*.test", 16,
            true);/*from  w w  w. j  a  v a 2 s.  co  m*/
    delegate.setParser(parser);

    assertNotNull(delegate.getParser());
    assertNotNull(parser.getMapFile());

    File test = new File(f.getAbsolutePath().substring(0, f.getAbsolutePath().lastIndexOf(File.separator)));
    assertTrue(test.isDirectory());

    try {
        File foundfile = delegate.findFile(test, "*.test");

    } catch (Exception ex) {

        fail("Parser did not find the file" + ex);
    } finally {
        f.deleteOnExit();
    }

}

From source file:ZipTransformTest.java

public void testByteArrayTransformer() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    File file2 = File.createTempFile("temp", null);
    try {//  w  w  w  .  j a va  2  s  .c om
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        ZipUtil.transformEntry(file1, name, new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }
        }, file2);

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file2, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
        FileUtils.deleteQuietly(file2);
    }
}

From source file:de.yaio.services.metaextract.server.extractor.TesseractExtractor.java

@Override
public String extractText(final InputStream input, final String fileName, final String lang)
        throws IOException, ExtractorException {
    File tmpFile;/*w w w.ja  v  a  2 s  .c  o  m*/
    tmpFile = File.createTempFile("metaextractor", "." + FilenameUtils.getExtension(fileName));
    tmpFile.deleteOnExit();
    Files.copy(input, tmpFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
    return this.extractText(tmpFile, lang);
}

From source file:io.druid.segment.loading.HdfsDataSegmentPullerTest.java

@BeforeClass
public static void setupStatic() throws IOException, ClassNotFoundException {
    hdfsTmpDir = File.createTempFile("hdfsHandlerTest", "dir");
    if (!hdfsTmpDir.delete()) {
        throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath());
    }//from   w w  w.  j  a  va 2  s .co  m
    conf = new Configuration(true);
    conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath());
    miniCluster = new MiniDFSCluster.Builder(conf).build();
    uriBase = miniCluster.getURI(0);

    final File tmpFile = File.createTempFile("hdfsHandlerTest", ".data");
    tmpFile.delete();
    try {
        Files.copy(new ByteArrayInputStream(pathByteContents), tmpFile.toPath());
        try (OutputStream stream = miniCluster.getFileSystem().create(filePath)) {
            Files.copy(tmpFile.toPath(), stream);
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:cc.recommenders.io.IoUtilsTest.java

@Test
public void randomFileIsSubfolderOfTmp() throws IOException {
    String actual = sut.getRandomTempFile();
    String expected = File.createTempFile(IoUtils.TEMP_PREFIX, "").getAbsolutePath();

    int len = expected.toString().indexOf(IoUtils.TEMP_PREFIX);

    String actual2 = actual.substring(0, len);
    String expected2 = expected.substring(0, len);

    assertEquals(expected2, actual2);// w  w w .j ava 2 s.  c om
}

From source file:fr.gael.ccsds.sip.archive.ZipArchiveManager.java

/**
 * Produces Zip compressed archive./*  w w  w .jav a2 s .  c  om*/
 */
@Override
public File copy(final File src, final File zip_file, final String dst) throws Exception {
    if (zip_file.exists()) {
        final FileInputStream fis = new FileInputStream(zip_file);
        final ZipArchiveInputStream zis = new ZipArchiveInputStream(fis);

        final File tempFile = File.createTempFile("updateZip", "zip");
        final FileOutputStream fos = new FileOutputStream(tempFile);
        final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);

        // copy the existing entries
        ZipArchiveEntry nextEntry;
        while ((nextEntry = zis.getNextZipEntry()) != null) {
            zos.putArchiveEntry(nextEntry);
            IOUtils.copy(zis, zos);
            zos.closeArchiveEntry();
        }

        // create the new entry
        final ZipArchiveEntry entry = new ZipArchiveEntry(src, dst);
        entry.setSize(src.length());
        zos.putArchiveEntry(entry);
        final FileInputStream sfis = new FileInputStream(src);
        IOUtils.copy(sfis, zos);
        sfis.close();
        zos.closeArchiveEntry();

        zos.finish();
        zis.close();
        fis.close();
        zos.close();

        // Rename the new file over the old
        boolean status = zip_file.delete();
        File saved_tempFile = tempFile;
        status = tempFile.renameTo(zip_file);

        // Copy the new file over the old if the renaming failed
        if (!status) {
            final FileInputStream tfis = new FileInputStream(saved_tempFile);
            final FileOutputStream tfos = new FileOutputStream(zip_file);

            final byte[] buf = new byte[1024];
            int i = 0;

            while ((i = tfis.read(buf)) != -1) {
                tfos.write(buf, 0, i);
            }

            tfis.close();
            tfos.close();

            saved_tempFile.delete();
        }

        return zip_file;

    } else {
        final FileOutputStream fos = new FileOutputStream(zip_file);
        final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);

        final ZipArchiveEntry entry = new ZipArchiveEntry(src, dst);
        entry.setSize(src.length());
        zos.putArchiveEntry(entry);

        final FileInputStream sfis = new FileInputStream(src);
        IOUtils.copy(sfis, zos);
        sfis.close();

        zos.closeArchiveEntry();

        zos.finish();
        zos.close();
        fos.close();
    }
    return zip_file;
}

From source file:com.ning.billing.dbi.MysqlTestingHelper.java

public void startMysql() throws IOException {
    // New socket on any free port
    final ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();//w  w  w .jav a2s.com
    socket.close();

    dbDir = File.createTempFile("mysql", "");
    dbDir.delete();
    dbDir.mkdir();
    mysqldResource = new MysqldResource(dbDir);

    final Map<String, String> dbOpts = new HashMap<String, String>();
    dbOpts.put(MysqldResourceI.PORT, Integer.toString(port));
    dbOpts.put(MysqldResourceI.INITIALIZE_USER, "true");
    dbOpts.put(MysqldResourceI.INITIALIZE_USER_NAME, USERNAME);
    dbOpts.put(MysqldResourceI.INITIALIZE_PASSWORD, PASSWORD);

    mysqldResource.start("test-mysqld-thread", dbOpts);
    if (!mysqldResource.isRunning()) {
        throw new IllegalStateException("MySQL did not start.");
    } else {
        log.info("MySQL running on port " + mysqldResource.getPort());
    }
}

From source file:com.ning.metrics.collector.processing.db.CollectorMysqlTestingHelper.java

public void startMysql() throws IOException {
    ServerSocket socket = new ServerSocket(0);

    port = socket.getLocalPort();/*from  w  w w . jav  a 2s  .  c o  m*/
    socket.close();

    dbDir = File.createTempFile("mysqldb", ".db");
    Assert.assertTrue(dbDir.delete());
    Assert.assertTrue(dbDir.mkdir());

    mysqldResource = new MysqldResource(dbDir);

    Map<String, String> dbOpts = new HashMap<String, String>();

    dbOpts.put(MysqldResourceI.PORT, Integer.toString(port));
    dbOpts.put(MysqldResourceI.INITIALIZE_USER, "true");
    dbOpts.put(MysqldResourceI.INITIALIZE_USER_NAME, USERNAME);
    dbOpts.put(MysqldResourceI.INITIALIZE_PASSWORD, PASSWORD);

    mysqldResource.start("test-mysqld-thread", dbOpts);

    if (!mysqldResource.isRunning()) {
        throw new IllegalStateException("MySQL did not start.");
    }
}