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:com.adaptris.util.stream.StreamUtil.java

/**
 * Read from the inputstream associated with the socket and write the data
 * straight out to a unique file in the specified directory
 *
 * @param input The inputstream to read from
 * @param expected the expected number of bytes
 * @param dir The directory in which to create the file
 * @return a File object corresponding to the temporary file that was created
 * @throws IOException if there was an creating the file
 *//*www  . j av  a  2  s. com*/
public static File createFile(InputStream input, int expected, String dir) throws IOException {

    File tempFile = null;
    if (isEmpty(dir)) {
        tempFile = File.createTempFile("tmp", "");
    } else {
        tempFile = File.createTempFile("tmp", "", new File(dir));
    }

    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile))) {
        copyStream(input, out, expected);
    }
    return tempFile;
}

From source file:com.asakusafw.shafu.core.util.IoUtils.java

/**
 * Creates a new temporary folder./*from  w  w  w  .  jav a  2  s  . c o m*/
 * @return the created folder
 * @throws IOException if failed to create a temporary folder
 */
public static File createTemporaryFolder() throws IOException {
    File file = File.createTempFile("dir", null); //$NON-NLS-1$
    if (file.delete() == false) {
        throw new IOException(MessageFormat.format(Messages.IoUtils_errorFailedToDeleteTemporaryFile, file));
    }
    if (file.mkdirs() == false) {
        throw new IOException(
                MessageFormat.format(Messages.IoUtils_errorFailedToCreateTemporaryDirectory, file));
    }
    return file;
}

From source file:ch.systemsx.cisd.openbis.generic.client.web.server.UploadedFilesBean.java

private final File createTempFile() throws IOException {
    final File tempFile = File.createTempFile(CLASS_SIMPLE_NAME, null);
    tempFile.deleteOnExit();/*from ww w  .j a  v a 2  s.c o m*/
    return tempFile;
}

From source file:io.rhiot.component.kura.deploymanager.InstallProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    byte[] bundleData = exchange.getIn().getBody(byte[].class);
    String topic = exchange.getIn().getHeader("DeployManager.topic", String.class);
    String bundleName = topic.substring(topic.lastIndexOf('/') + 1) + ".jar";

    File temporaryBundle = File.createTempFile("kura", "deploy");
    write(bundleData, new FileOutputStream(temporaryBundle));
    temporaryBundle.renameTo(new File(deployDirectory, bundleName));
}

From source file:cc.kave.commons.utils.json.JsonUtilsTest.java

@Before
public void setup() throws IOException {
    tmpFile = File.createTempFile("test-", ".json");
}

From source file:com.htmlhifive.pitalium.common.util.JSONUtilsTest.java

@Test
public void testWriteValue() throws Exception {
    file = File.createTempFile("tmp", null);
    JSONUtils.writeValue(file, data);/*from   www  .ja  v  a 2s.  co  m*/

    String result = FileUtils.readFileToString(file);
    assertThat(result, is("{\"a\":\"b\"}"));
}

From source file:eu.planets_project.ifr.core.techreg.formats.DroidConfig.java

/**
 * @return The location of the DROID signature file taken from the
 *          Droid configuration properties file
 *///from ww w. ja va  2 s  . c om
public static String getSigFileLocation() {
    // String to hold the location
    String sigFileLocation = null;
    // Get the configuration object from the ServiceConfig util
    try {
        Configuration conf = ServiceConfig.getConfiguration(COMMON_CONF_FILE_NAME);
        // Create the file name from the properties
        sigFileLocation = conf.getString(SIG_FILE_LOC_KEY) + File.separator + conf.getString(SIG_FILE_NAME_KEY);
    } catch (ConfigurationException e) {
        log.severe("Could not find configuration file! " + e);
    }
    log.info("DROID Signature File location:" + sigFileLocation);
    // Check if the sigFileLocation is sane, and override with internal resource if not:
    File sfl = null;
    if (sigFileLocation != null)
        sfl = new File(sigFileLocation);
    if (sfl == null || !sfl.exists() || !sfl.isFile()) {
        try {
            File tmp = File.createTempFile("DroidSigFile", "xml");
            tmp.deleteOnExit();
            IOUtils.copy(DroidConfig.class.getResourceAsStream("/droid/DROID_SignatureFile.xml"),
                    new FileOutputStream(tmp));
            sigFileLocation = tmp.getAbsolutePath();
            log.info("Wrote cached Droid sig file to " + sigFileLocation);
        } catch (IOException e) {
            e.printStackTrace();
            log.severe("Could not generate external Droid Sig File.");
        }
    }
    return sigFileLocation;
}

From source file:com.creactiviti.piper.core.taskhandler.script.Bash.java

@Override
public String handle(Task aTask) throws Exception {
    File scriptFile = File.createTempFile("_script", ".sh");
    File logFile = File.createTempFile("log", null);
    FileUtils.writeStringToFile(scriptFile, aTask.getRequiredString("script"));
    try (PrintStream stream = new PrintStream(logFile);) {
        Process chmod = Runtime.getRuntime().exec(String.format("chmod u+x %s", scriptFile.getAbsolutePath()));
        int chmodRetCode = chmod.waitFor();
        if (chmodRetCode != 0) {
            throw new ExecuteException("Failed to chmod", chmodRetCode);
        }/*from w ww  . j  ava  2 s.com*/
        CommandLine cmd = new CommandLine(scriptFile.getAbsolutePath());
        logger.debug("{}", cmd);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);
        return FileUtils.readFileToString(logFile);
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(logFile)));
    } finally {
        FileUtils.deleteQuietly(logFile);
        FileUtils.deleteQuietly(scriptFile);
    }
}

From source file:com.metadave.stow.TestStow.java

@Test
public void testGen() throws Exception {
    InputStream is = this.getClass().getResourceAsStream("/Stow.stg");
    File f = File.createTempFile("stow", "test.stg");
    String root = f.getParent();//from w w  w .j a v a  2 s  .  c  o  m
    String classdir = root + File.separator + "stowtest";

    String stgPath = f.getAbsolutePath();
    String stowStg = org.apache.commons.io.IOUtils.toString(is);

    org.apache.commons.io.FileUtils.writeStringToFile(f, stowStg);

    File d = new File(classdir);
    d.mkdirs();

    Stow.generateObjects(stgPath, "stowtest", "Test", classdir);

    File testSTBean = new File(classdir + File.separator + "TestSTBean.java");
    assertTrue(testSTBean.exists());

    File testSTAccessor = new File(classdir + File.separator + "TestSTAccessor.java");
    assertTrue(testSTAccessor.exists());

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, testSTBean.getAbsolutePath());
    compiler.run(null, null, null, testSTAccessor.getAbsolutePath());

    File testSTAccessorClass = new File(classdir + File.separator + "TestSTAccessor.class");
    assertTrue(testSTAccessorClass.exists());

    File testSTBeanClass = new File(classdir + File.separator + "TestSTBean.class");
    assertTrue(testSTBeanClass.exists());

    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File(root).toURI().toURL() });
    Class<?> cls = Class.forName("stowtest.TestSTBean", true, classLoader);

    Constructor<?> c = cls.getConstructors()[0];
    STGroup stg = new STGroupFile(f.getAbsolutePath());
    Object o = c.newInstance(stg);

    Set<String> methods = new HashSet<String>();
    methods.add("addPackage");
    methods.add("addBeanClass");
    methods.add("addTemplateName");
    methods.add("addAccessor");

    int count = 0;
    for (Method m : o.getClass().getMethods()) {
        if (methods.contains(m.getName())) {
            count++;
        }
    }
    assertEquals("Look for 8 generated methods", 8, count);
}

From source file:annis.visualizers.component.graph.DebugVisualizer.java

@Override
public void createDotContent(VisualizerInput input, StringBuilder sb) {
    try {//from w  w w.  j a  v  a  2  s .  co  m
        File tmpFile = File.createTempFile("annisdebugvis", ".dot");
        tmpFile.deleteOnExit();
        Salt2DOT converter = new Salt2DOT();
        converter.salt2Dot(input.getDocument().getSDocumentGraph(),
                URI.createFileURI(tmpFile.getCanonicalPath()));

        sb.append(FileUtils.readFileToString(tmpFile));

        if (!tmpFile.delete()) {
            log.warn("Cannot delete " + tmpFile.getAbsolutePath());
        }
    } catch (IOException ex) {
        log.error("could not create temporary file for dot", ex);
    }
}