Java Code Examples for java.io.File.createTempFile()

The following are Jave code examples for showing how to use createTempFile() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: QDrill   File: TestDrillFileSystem.java   View Source Code Vote up 6 votes
@BeforeClass
public static void createTempFile() throws Exception {

  File tempFile;
  while (true) {
    tempFile = File.createTempFile("drillFSTest", ".txt");
    if (tempFile.exists()) {
      boolean success = tempFile.delete();
      if (success) {
        break;
      }
    }
  }

  // Write some data
  PrintWriter printWriter = new PrintWriter(tempFile);
  for (int i=1; i<=200000; i++) {
    printWriter.println (String.format("%d, key_%d", i, i));
  }
  printWriter.close();

  tempFilePath = tempFile.getPath();
}
 
Example 2
Project: big_data   File: EJob.java   View Source Code Vote up 6 votes
/**
 * 创建临时文件*.jar
 * 
 * @param root
 * @return
 * @throws IOException
 */
public static File createTempJar(String root) throws IOException {
    if (!new File(root).exists()) {
        return null;
    }

    final File jarFile = File.createTempFile("EJob-", ".jar", new File(System
            .getProperty("java.io.tmpdir")));

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            jarFile.delete();
        }
    });

    JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile));
    createTempJarInner(out, new File(root), "");
    out.flush();
    out.close();
    return jarFile;
}
 
Example 3
Project: incubator-netbeans   File: LogRecordsRepairTest.java   View Source Code Vote up 6 votes
private File createTempFileFrom(String resource) throws IOException {
    InputStream is = getClass().getResourceAsStream("resources/"+resource);
    File f = File.createTempFile("LR_", resource);
    f.deleteOnExit();
    OutputStream out = new FileOutputStream(f);
    try {
        byte[] buffer = new byte[1024];
        int l;
        while((l = is.read(buffer)) > 0) {
            out.write(buffer, 0, l);
        }
    } finally {
        is.close();
        out.close();
    }
    return f;
}
 
Example 4
Project: jdk8u-jdk   File: Load.java   View Source Code Vote up 6 votes
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    test_file = File.createTempFile("test", ".raw");
    FileOutputStream fos = new FileOutputStream(test_file);
    fos.write(test_byte_array);
}
 
Example 5
Project: openjdk-jdk10   File: FileJcmdExecutor.java   View Source Code Vote up 6 votes
private File createTempFile() {
    try {
        File cmdFile = File.createTempFile("input", "jcmd");
        cmdFile.deleteOnExit();
        return cmdFile;
    } catch (IOException e) {
        throw new CommandExecutorException("Could not create temporary file", e);
    }
}
 
Example 6
Project: openjdk-jdk10   File: Skip.java   View Source Code Vote up 6 votes
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    test_file = File.createTempFile("test", ".raw");
    try (FileOutputStream fos = new FileOutputStream(test_file)) {
        fos.write(test_byte_array);
    }
}
 
Example 7
Project: https-github.com-apache-zookeeper   File: ClientBase.java   View Source Code Vote up 5 votes
static File createTmpDir(File parentDir, boolean createInitFile) throws IOException {
    File tmpFile = File.createTempFile("test", ".junit", parentDir);
    // don't delete tmpFile - this ensures we don't attempt to create
    // a tmpDir with a duplicate name
    File tmpDir = new File(tmpFile + ".dir");
    Assert.assertFalse(tmpDir.exists()); // never true if tmpfile does it's job
    Assert.assertTrue(tmpDir.mkdirs());

    // todo not every tmp directory needs this file
    if (createInitFile) {
        createInitializeFile(tmpDir);
    }

    return tmpDir;
}
 
Example 8
Project: matplotlib4j   File: SaveFigTest.java   View Source Code Vote up 5 votes
@Test
public void testSaveFigNoImpactToShow() throws IOException, PythonExecutionException {
    File tmpFile = File.createTempFile("savefig", ".png");
    tmpFile.deleteOnExit();

    Plot plt = new PlotImpl(DRY_RUN);
    plt.plot().add(Arrays.asList(1.3, 2));
    plt.title("Title!");
    plt.savefig(tmpFile.getAbsolutePath());
    plt.executeSilently();
    plt.show();

    Assert.assertTrue(tmpFile.exists());
}
 
Example 9
Project: stvs   File: VerificationError.java   View Source Code Vote up 5 votes
/**
 * Construct a new VerificationError from an Exception (which was thrown while launching/managing
 * the verification. These will typically not come from the verification engine itself).
 *
 * @param ex The exception to construct a VerificationError from
 */
public VerificationError(Exception ex) {
  this.reason = Reason.EXCEPTION;
  try {
    logFile = File.createTempFile("verification-exception", "");
    PrintWriter writer = new PrintWriter(
        new OutputStreamWriter(new FileOutputStream(logFile), StandardCharsets.UTF_8), true);
    ex.printStackTrace(writer);
  } catch (IOException exception) {
    // Do nothing if writing the exception to the log throws an exception
    logFile = null;
  }
  errorMessages.put(Reason.EXCEPTION, ex.getMessage());
}
 
Example 10
Project: Face_Animate   File: BitmapUtils.java   View Source Code Vote up 5 votes
/**
 * Creates the temporary image file in the cache directory.
 *
 * @return The temporary image file.
 * @throws IOException Thrown if there is an error creating the file
 */
static File createTempImageFile(Context context) throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    //Returns the absolute path to the application specific cache directory on the filesystem.
    File storageDir = context.getExternalCacheDir();

    return File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
}
 
Example 11
Project: etomica   File: GraphMap.java   View Source Code Vote up 5 votes
public void imageOut(String fileName) {

    File f = null;
    try {
      f = File.createTempFile("tmp_", "svg");
      FileOutputStream fs = new FileOutputStream(f);
      streamOut(fs);
      fs.flush();
      fs.close();
      String[] options = new String[13];
      // destination
      options[0] = Main.CL_OPTION_OUTPUT;
      options[1] = fileName;
      // destination type
      options[2] = Main.CL_OPTION_MIME_TYPE;
      options[3] = getMimeType(fileName);
      // quality (for JPEG)
      options[4] = Main.CL_OPTION_QUALITY;
      options[5] = "0.8";
      // resolution
      options[6] = Main.CL_OPTION_DPI;
      options[7] = "300";
      // resolution
      options[8] = Main.CL_OPTION_WIDTH;
      options[9] = "1024";
      // resolution
      options[10] = Main.CL_OPTION_BACKGROUND_COLOR;
      options[11] = "255.255.255.255";
      // input file
      options[12] = f.getAbsolutePath();
      // convert
      Main c = new Main(options);
      c.execute();
      // remove temporary file
      f.delete();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
 
Example 12
Project: GitHub   File: ContentTypeForHttpEntitySample.java   View Source Code Vote up 5 votes
@Override
public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) {
    RequestParams rParams = new RequestParams();
    rParams.put("sample_key", "Sample String");
    try {
        File sample_file = File.createTempFile("temp_", "_handled", getCacheDir());
        rParams.put("sample_file", sample_file);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Cannot add sample file", e);
    }
    return client.post(this, URL, headers, rParams, "multipart/form-data", responseHandler);
}
 
Example 13
Project: ZooKeeper   File: ClientBase.java   View Source Code Vote up 5 votes
static File createTmpDir(File parentDir) throws IOException {
    File tmpFile = File.createTempFile("test", ".junit", parentDir);
    // don't delete tmpFile - this ensures we don't attempt to create
    // a tmpDir with a duplicate name
    File tmpDir = new File(tmpFile + ".dir");
    Assert.assertFalse(tmpDir.exists()); // never true if tmpfile does it's job
    Assert.assertTrue(tmpDir.mkdirs());

    return tmpDir;
}
 
Example 14
Project: uidcore-java   File: UniquidNodeImplBuilderTest.java   View Source Code Vote up 5 votes
@Test
public void testBuild() throws Exception {
	
	@SuppressWarnings("rawtypes")
	UniquidNodeImpl.UniquidNodeBuilder builder = new UniquidNodeImpl.UniquidNodeBuilder();
	
	NetworkParameters parameters = UniquidRegTest.get();
	File providerFile = File.createTempFile("provider", ".wallet");
	File userFile = File.createTempFile("user", ".wallet");
	File chainFile = File.createTempFile("chain", ".chain");
	File userChainFile = File.createTempFile("userchain", ".chain");
	RegisterFactory dummyRegister = new DummyRegisterFactory(null, null, new DummyTransactionManager());
	String machineName = "machineName";

	builder.setNetworkParameters(parameters);
	builder.setProviderFile(providerFile);
	builder.setUserFile(userFile);
	builder.setProviderChainFile(chainFile);
	builder.setUserChainFile(userChainFile);
	builder.setRegisterFactory(dummyRegister);
	builder.setNodeName(machineName);
	
	UniquidNodeImpl uniquidNode = builder.build();
	
	Assert.assertNotNull(uniquidNode);
	
}
 
Example 15
Project: monarch   File: FileUtilJUnitTest.java   View Source Code Vote up 5 votes
@Test
public void testDeleteDir() throws IOException {
  File dir = new File("testDirName");
  dir.mkdir();
  File file = File.createTempFile("testFile", null, dir);
  assertTrue(dir.exists());
  assertTrue(file.exists());
  FileUtil.delete(dir);
  assertFalse(file.exists());
  assertFalse(dir.exists());
}
 
Example 16
Project: browser   File: Utils.java   View Source Code Vote up 5 votes
@SuppressLint("SimpleDateFormat")
public static File createImageFile() throws IOException {
	// Create an image file name
	String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	String imageFileName = "JPEG_" + timeStamp + "_";
	File storageDir = Environment
			.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
	return File.createTempFile(imageFileName, /* prefix */
			".jpg", /* suffix */
			storageDir /* directory */
	);
}
 
Example 17
Project: minijax   File: LiquibaseHelperTest.java   View Source Code Vote up 4 votes
@Test
public void testEndToEnd() throws Exception {
    final File targetFile = File.createTempFile("target", null);
    final File referenceFile = File.createTempFile("reference", null);
    final String targetUrl = "jdbc:h2:" + targetFile.getAbsolutePath();
    final String referenceUrl = "jdbc:h2:" + referenceFile.getAbsolutePath();
    final String masterChangeLogResourceName = "changes-" + System.currentTimeMillis() + ".xml";
    final File migrationsDir = new File(TEST_RESOURCES, "migrations");
    final File masterChangeLogFile = new File(migrationsDir, masterChangeLogResourceName);

    final Map<String, String> props = new HashMap<>();
    props.put(MinijaxProperties.PERSISTENCE_UNIT_NAME, "testdb");
    props.put(MinijaxProperties.DB_DRIVER, "org.h2.jdbcx.JdbcDataSource");
    props.put(MinijaxProperties.DB_URL, targetUrl);
    props.put(MinijaxProperties.DB_REFERENCE_URL, referenceUrl);
    props.put(MinijaxProperties.DB_USERNAME, "");
    props.put(MinijaxProperties.DB_PASSWORD, "");

    // Verify that both databases are empty and that the changelog does not exist
    assertTrue(getTables(targetUrl).isEmpty());
    assertTrue(getTables(referenceUrl).isEmpty());
    assertFalse(masterChangeLogFile.exists());

    final FileSystemResourceAccessor accessor = new FileSystemResourceAccessor(TEST_RESOURCES.getAbsolutePath()) {
        @Override
        protected void init() {
            try {
                addRootPath(TEST_RESOURCES.getAbsoluteFile().toURI().toURL());
                addRootPath(masterChangeLogFile.getAbsoluteFile().toURI().toURL());
            } catch (final MalformedURLException ex) {
                ex.printStackTrace();
            }
        }
    };

    final LiquibaseHelper m = new LiquibaseHelper(
            props,
            accessor,
            TEST_RESOURCES,
            masterChangeLogResourceName);

    // Generate the migration
    final File firstGeneratedChangeLog = m.generateMigrations();
    assertTrue(firstGeneratedChangeLog.exists());

    // Verify that the "target" database is still empty
    assertTrue(getTables(targetUrl).isEmpty());

    // Verify that the "reference" database now has the "WIDGET" table
    assertEquals(Arrays.asList("WIDGET"), getTables(referenceUrl));

    // Verify that the changelog file now exists
    assertTrue(masterChangeLogFile.exists());

    // Run the migration
    m.migrate();

    // Verify that the "target" database now has Liquibase tables and the "WIDGET" table
    assertEquals(Arrays.asList("DATABASECHANGELOG", "DATABASECHANGELOGLOCK", "WIDGET"), getTables(targetUrl));

    // Generate the migration again (should be no-op)
    final File secondGeneratedChangeLog = m.generateMigrations();
    assertNull(secondGeneratedChangeLog);

    // Verify that the "reference" database is still only the "WIDGET" table
    assertEquals(Arrays.asList("WIDGET"), getTables(referenceUrl));

    // Run the migration again (should be no-op)
    m.migrate();

    // Verify that the "target" database still has only Liquibase tables and the "WIDGET" table
    assertEquals(Arrays.asList("DATABASECHANGELOG", "DATABASECHANGELOGLOCK", "WIDGET"), getTables(targetUrl));

    // Cleanup
    deleteDatabase(targetFile);
    deleteDatabase(referenceFile);
    masterChangeLogFile.delete();
    firstGeneratedChangeLog.delete();
    migrationsDir.delete();
}
 
Example 18
Project: alfresco-file-transfer-receiver   File: FSRScriptRunnable.java   View Source Code Vote up 4 votes
public void run()
    {
        try
        {
        	File tempFile = File.createTempFile("deployment", "txt");
//            Writer out = new FileWriter(tempFile);
//            for (DeployedFile file : fDeployment)
//            {
//                out.write(file.getType().toString() + " '" + file.getPath().replaceAll("'", "\\\\'") + "' " + file.getGuid() + "\n");
//            }
//            out.close();
        	Runtime runTime = Runtime.getRuntime();
            int commandLength = 2 + fArguments.size();
            String[] command = new String[commandLength];
            command[0] = fProgram;
            command[1] = tempFile.getAbsolutePath();
            int off = 2;
            for (String arg : fArguments)
            {
                command[off++] = arg;
            }
            Map<String, String> envMap = System.getenv();
            String[] env = new String[envMap.size()];
            off = 0;
            for (Map.Entry<String, String> entry : envMap.entrySet())
            {
                env[off++] = entry.getKey() + '=' + entry.getValue();
            }
            Process process = runTime.exec(command, env, new File(fDirectory));
            
            StreamDigester errorDigester = new StreamDigester(process.getErrorStream());
            StreamDigester outputDigester = new StreamDigester(process.getInputStream());
            errorDigester.start();
            outputDigester.start();
            
            process.waitFor();
            tempFile.delete();
        }
        catch (IOException e)
        {
        	//
        }
        catch (InterruptedException inte)
        {
        	//
        }
    }
 
Example 19
Project: XERUNG   File: CropUtil.java   View Source Code Vote up 4 votes
private static String getTempFilename(Context context) throws IOException {
    File outputDir = context.getCacheDir();
    File outputFile = File.createTempFile("image", "tmp", outputDir);
    return outputFile.getAbsolutePath();
}
 
Example 20
Project: springboot-shiro-cas-mybatis   File: InMemoryTestLdapDirectoryServer.java   View Source Code Vote up 4 votes
/**
 * Instantiates a new Ldap directory server.
 * Parameters need to be streams so they can be read from JARs.
 */
public InMemoryTestLdapDirectoryServer(final InputStream properties,
                                       final InputStream ldifFile,
                                       final InputStream schemaFile) {
    try {
        final Properties p = new Properties();
        p.load(properties);

        final InMemoryDirectoryServerConfig config =
                new InMemoryDirectoryServerConfig(p.getProperty("ldap.rootDn"));
        config.addAdditionalBindCredentials(p.getProperty("ldap.managerDn"), p.getProperty("ldap.managerPassword"));

        final File keystoreFile = File.createTempFile("key", "store");
        try (OutputStream outputStream = new FileOutputStream(keystoreFile)) {
            IOUtils.copy(new ClassPathResource("/ldapServerTrustStore").getInputStream(), outputStream);
        }

        final String serverKeyStorePath = keystoreFile.getCanonicalPath();
        final SSLUtil serverSSLUtil = new SSLUtil(
                new KeyStoreKeyManager(serverKeyStorePath, "changeit".toCharArray()), new TrustStoreTrustManager(serverKeyStorePath));
        final SSLUtil clientSSLUtil = new SSLUtil(new TrustStoreTrustManager(serverKeyStorePath));
        config.setListenerConfigs(
                InMemoryListenerConfig.createLDAPConfig("LDAP", // Listener name
                        null, // Listen address. (null = listen on all interfaces)
                        1389, // Listen port (0 = automatically choose an available port)
                        serverSSLUtil.createSSLSocketFactory()), // StartTLS factory
                InMemoryListenerConfig.createLDAPSConfig("LDAPS", // Listener name
                        null, // Listen address. (null = listen on all interfaces)
                        1636, // Listen port (0 = automatically choose an available port)
                        serverSSLUtil.createSSLServerSocketFactory(), // Server factory
                        clientSSLUtil.createSSLSocketFactory())); // Client factory

        config.setEnforceSingleStructuralObjectClass(false);
        config.setEnforceAttributeSyntaxCompliance(true);


        final File file = File.createTempFile("ldap", "schema");
        try (OutputStream outputStream = new FileOutputStream(file)) {
            IOUtils.copy(schemaFile, outputStream);
        }

        final Schema s = Schema.mergeSchemas(Schema.getSchema(file));
        config.setSchema(s);


        this.directoryServer = new InMemoryDirectoryServer(config);
        LOGGER.debug("Populating directory...");

        final File ldif = File.createTempFile("ldiff", "file");
        try (OutputStream outputStream = new FileOutputStream(ldif)) {
            IOUtils.copy(ldifFile, outputStream);
        }

        this.directoryServer.importFromLDIF(true, ldif.getCanonicalPath());
        this.directoryServer.restartServer();

        final LDAPConnection c = getConnection();
        LOGGER.debug("Connected to {}:{}", c.getConnectedAddress(), c.getConnectedPort());

        populateDefaultEntries(c);

        c.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}