java.io.File#createTempFile ( )源码实例Demo

下面列出了java.io.File#createTempFile ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jdk8u_jdk   文件: BandStructure.java
static OutputStream getDumpStream(String name, int seq, String ext, Object b) throws IOException {
    if (dumpDir == null) {
        dumpDir = File.createTempFile("BD_", "", new File("."));
        dumpDir.delete();
        if (dumpDir.mkdir())
            Utils.log.info("Dumping bands to "+dumpDir);
    }
    name = name.replace('(', ' ').replace(')', ' ');
    name = name.replace('/', ' ');
    name = name.replace('*', ' ');
    name = name.trim().replace(' ','_');
    name = ((10000+seq) + "_" + name).substring(1);
    File dumpFile = new File(dumpDir, name+ext);
    Utils.log.info("Dumping "+b+" to "+dumpFile);
    return new BufferedOutputStream(new FileOutputStream(dumpFile));
}
 
源代码2 项目: spork   文件: TestFilterOpNumeric.java
@Test
public void testNestedBinCond() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for(int i = 0; i < LOOP_COUNT; i++) {
        ps.println(i + "\t" + i + "\t1");
    }
    ps.close();
    pig.registerQuery("A=load '"
            + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext())) + "';");
    String query = "A = foreach A generate (($0 < 10 or $0 < 9)?(($1 >= 5 and $1 >= 4) ? 2: 1) : 0);";
    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    int count =0;
    while(it.hasNext()) {
        Tuple t = it.next();
        Integer first = (Integer)t.get(0);
        count+=first;
        assertTrue(first == 1 || first == 2 || first == 0);

    }
    assertEquals("expected count of 15", 15, count);
}
 
源代码3 项目: ambry   文件: RouterServerSSLTest.java
@BeforeClass
public static void initializeTests() throws Exception {
  File trustStoreFile = File.createTempFile("truststore", ".jks");
  String sslEnabledDataCentersStr = "DC1,DC2,DC3";
  Properties serverSSLProps = new Properties();
  TestSSLUtils.addSSLProperties(serverSSLProps, sslEnabledDataCentersStr, SSLFactory.Mode.SERVER, trustStoreFile,
      "server");
  TestSSLUtils.addHttp2Properties(serverSSLProps, SSLFactory.Mode.SERVER, true);
  Properties routerProps = getRouterProperties("DC1");
  TestSSLUtils.addSSLProperties(routerProps, sslEnabledDataCentersStr, SSLFactory.Mode.CLIENT, trustStoreFile,
      "router-client");
  sslCluster = new MockCluster(serverSSLProps, false, SystemTime.getInstance());
  MockNotificationSystem notificationSystem = new MockNotificationSystem(sslCluster.getClusterMap());
  sslCluster.initializeServers(notificationSystem);
  sslCluster.startServers();
  MockClusterMap routerClusterMap = sslCluster.getClusterMap();
  // MockClusterMap returns a new registry by default. This is to ensure that each node (server, router and so on,
  // get a different registry. But at this point all server nodes have been initialized, and we want the router and
  // its components, which are going to be created, to use the same registry.
  routerClusterMap.createAndSetPermanentMetricRegistry();
  testFramework = new RouterServerTestFramework(routerProps, routerClusterMap, notificationSystem);
  routerMetricRegistry = routerClusterMap.getMetricRegistry();
}
 
源代码4 项目: gogs-webhook-plugin   文件: GogsWebHookTest.java
@Test
public void whenUriDoesNotContainUrlNameMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn("job=myJob");


    MockServletInputStream inputStream = new MockServletInputStream("body");
    when(staplerRequest.getInputStream()).thenReturn(inputStream);
    when(staplerRequest.getRequestURI()).thenReturn("/badUri/aaa");

    //perform the testÎ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(404);

    String expectedOutput = "No payload or URI contains invalid entries.";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
源代码5 项目: openjdk-jdk9   文件: SubbufferLongLong.java
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);
    }
}
 
源代码6 项目: j2objc   文件: PosixTest.java
public void testPreadBytes() throws Exception{
  final String testString = "hello, world!";
  byte[] bytesToWrite = testString.getBytes("UTF-8");
  ByteBuffer buf = ByteBuffer.allocate(bytesToWrite.length);

  File tmpFile = File.createTempFile("preadbug-", ".tmp");
  tmpFile.deleteOnExit();

  try (
      FileOutputStream fos = new FileOutputStream(tmpFile)) {
    fos.write(bytesToWrite);
  }

  try (
      RandomAccessFile raf = new RandomAccessFile(tmpFile, "r");
      FileChannel channel = raf.getChannel()) {
    channel.read(buf, 0);
  }

  String dstString = new String(buf.array(), "UTF-8");
  assertEquals(testString, dstString);
}
 
源代码7 项目: openjdk-jdk8u-backup   文件: NullArgs.java
public static void main(String[] args) throws Exception {

        for (int i = 0;; i++) {
            try {
                switch (i) {
                case 0:  new File((String)null);  break;
                case 1:  new File((String)null, null);  break;
                case 2:  new File((File)null, null);  break;
                case 3:  File.createTempFile(null, null, null);  break;
                case 4:  File.createTempFile(null, null);  break;
                case 5:  new File("foo").compareTo(null);  break;
                case 6:  new File("foo").renameTo(null);  break;
                default:
                    System.err.println();
                    return;
                }
            } catch (NullPointerException x) {
                System.err.print(i + " ");
                continue;
            }
            throw new Exception("NullPointerException not thrown (case " +
                                i + ")");
        }

    }
 
源代码8 项目: TencentKona-8   文件: ScanDirConfigTest.java
/**
 * Test of getXmlConfigString method, of class com.sun.jmx.examples.scandir.ScanDirConfig.
 */
public void testGetXmlConfigString() throws Exception {
    System.out.println("getXmlConfigString");

    try {
        final File file = File.createTempFile("testconf",".xml");
        final ScanDirConfig instance = new ScanDirConfig(file.getAbsolutePath());
        final ScanManagerConfig bean =
            new  ScanManagerConfig("testGetXmlConfigString");
        final DirectoryScannerConfig dir =
            new DirectoryScannerConfig("tmp");
        dir.setRootDirectory(file.getParent());
        bean.putScan(dir);
        instance.setConfiguration(bean);
        System.out.println("Expected: " + XmlConfigUtils.toString(bean));
        System.out.println("Received: " +
                instance.getConfiguration().toString());
        assertEquals(XmlConfigUtils.toString(bean),
            instance.getConfiguration().toString());
    } catch (Exception x) {
        x.printStackTrace();
        throw x;
    }
}
 
源代码9 项目: lsmtree   文件: TestStore.java
@Override
public void setUp() throws Exception {
    tmpDir = File.createTempFile("tmp", "", new File("."));
    tmpDir.delete();
    tmpDir.mkdirs();
    String treeSizeStr = System.getProperty("lsmtree.test.size");
    treeSize = "large".equals(treeSizeStr) ? LARGE_TREE_SIZE : SMALL_TREE_SIZE;
}
 
public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext context =
            SpringApplication.run(LogServiceApplication.class, args);

    LogService logsService = context.getBean(LogService.class);
    FileService fileService = context.getBean(FileService.class);

    File tempFile = File.createTempFile("LogServiceApplication", ".tmp");
    tempFile.deleteOnExit();

    fileService.writeTo(tempFile.getAbsolutePath(), logsService.stream());

    RatpackServer.start(server ->
            server.handlers(chain ->
                    chain.all(ctx -> {

                        Publisher<String> logs = logsService.stream();

                        ServerSentEvents events = serverSentEvents(
                                logs,
                                event -> event.id(Objects::toString)
                                              .event("log")
                                              .data(Function.identity())
                        );

                        ctx.render(events);
                    })
            )
    );
}
 
源代码11 项目: java-stratum   文件: StratumChainTest.java
@Before
public void setUp() throws IOException {
    File file = File.createTempFile("stratum-chain", ".chain");
    client = createMock(StratumClient.class);
    expect(client.getHeadersQueue()).andStubReturn(null);
    params = NetworkParameters.fromID(NetworkParameters.ID_UNITTESTNET);
    //new CheckpointManager(params, new ByteArrayInputStream("TXT CHECKPOINTS 1\n0\n0\n".getBytes("UTF-8")))
    store = new HeadersStore(params, file, null, null);
    chain = new StratumChain(params, store, client);
}
 
源代码12 项目: titus-control-plane   文件: IOExtTest.java
@Test
public void testReadLines() throws Exception {
    File file = File.createTempFile("junit", ".txt", new File("build"));
    try (Writer fwr = new FileWriter(file)) {
        fwr.write("line1\n");
        fwr.write("line2");
    }

    List<String> lines = IOExt.readLines(file);
    assertThat(lines).containsExactly("line1", "line2");
}
 
源代码13 项目: incubator-tajo   文件: S3OutputStream.java
private File newBackupFile() throws IOException {
  File dir = new File(conf.get("fs.s3.buffer.dir"));
  if (!dir.exists() && !dir.mkdirs()) {
    throw new IOException("Cannot create S3 buffer directory: " + dir);
  }
  File result = File.createTempFile("output-", ".tmp", dir);
  result.deleteOnExit();
  return result;
}
 
@Before
public void setup() throws IOException {
  testData = new byte[128];
  for (int x = 0; x < 128; x++) {
    testData[x] = (byte) x;
  }
  tempFile = File.createTempFile("ra-fost", "tmp");
  tempFile.deleteOnExit();
}
 
源代码15 项目: openjdk-jdk8u   文件: P12SecretKey.java
private void run(String keystoreType) throws Exception {
    char[] pw = "password".toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(null, pw);

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey key = kg.generateKey();

    KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
    KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
    ks.setEntry(ALIAS, ske, kspp);

    File ksFile = File.createTempFile("test", ".test");
    try (FileOutputStream fos = new FileOutputStream(ksFile)) {
        ks.store(fos, pw);
        fos.flush();
    }

    // now see if we can get it back
    try (FileInputStream fis = new FileInputStream(ksFile)) {
        KeyStore ks2 = KeyStore.getInstance(keystoreType);
        ks2.load(fis, pw);
        KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
        SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
        if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
            System.err.println("OK: worked just fine with " + keystoreType +
                               " keystore");
        } else {
            System.err.println("ERROR: keys are NOT equal after storing in "
                               + keystoreType + " keystore");
        }
    }
}
 
源代码16 项目: portals-pluto   文件: EarAssemblerTest.java
public void testEarAssemblyToTempDir() throws Exception {
    AssemblerConfig config = new AssemblerConfig();
    config.setSource( earFile );
    File assembledEar = File.createTempFile( earFile.getName(), ".ear" ); 
    config.setDestination( assembledEar );
    EarAssembler assembler = new EarAssembler();
    assembler.assemble( config );
    validateEarAssembly( assembledEar );
    assembledEar.delete();
}
 
源代码17 项目: commons-imaging   文件: IptcAddTest.java
@ParameterizedTest
@MethodSource("data")
public void testAddIptcData(File imageFile) throws Exception {
    final ByteSource byteSource = new ByteSourceFile(imageFile);

    final Map<String, Object> params = new HashMap<>();
    final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
    params.put(ImagingConstants.PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));

    final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
    if (metadata == null) {
        // FIXME select only files with meta for this test
        return;
    }

    final List<IptcBlock> newBlocks = new ArrayList<>(metadata.photoshopApp13Data.getNonIptcBlocks());
    final List<IptcRecord> oldRecords = metadata.photoshopApp13Data.getRecords();

    final List<IptcRecord> newRecords = new ArrayList<>();
    for (final IptcRecord record : oldRecords) {
        if (record.iptcType != IptcTypes.CITY
                && record.iptcType != IptcTypes.CREDIT) {
            newRecords.add(record);
        }
    }

    newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
    newRecords.add(new IptcRecord(IptcTypes.CREDIT, "William Sorensen"));

    final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords, newBlocks);

    final File updated = File.createTempFile(imageFile.getName() + ".iptc.add.", ".jpg");
    try (FileOutputStream fos = new FileOutputStream(updated);
            OutputStream os = new BufferedOutputStream(fos)) {
        new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
    }

    final ByteSource updateByteSource = new ByteSourceFile(updated);
    final JpegPhotoshopMetadata outMetadata = new JpegImageParser().getPhotoshopMetadata(
            updateByteSource, params);

    assertNotNull(outMetadata);
    assertTrue(outMetadata.getItems().size() == newRecords.size());
}
 
源代码18 项目: ambry   文件: StorageManagerTest.java
/**
 * Test add new BlobStore with given {@link ReplicaId}.
 */
@Test
public void addBlobStoreTest() throws Exception {
  generateConfigs(true, false);
  MockDataNodeId localNode = clusterMap.getDataNodes().get(0);
  List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode);
  int newMountPathIndex = 3;
  // add new MountPath to local node
  File f = File.createTempFile("ambry", ".tmp");
  File mountFile =
      new File(f.getParent(), "mountpathfile" + MockClusterMap.PLAIN_TEXT_PORT_START_NUMBER + newMountPathIndex);
  MockClusterMap.deleteFileOrDirectory(mountFile);
  assertTrue("Couldn't create mount path directory", mountFile.mkdir());
  localNode.addMountPaths(Collections.singletonList(mountFile.getAbsolutePath()));
  PartitionId newPartition1 =
      new MockPartitionId(10L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), newMountPathIndex);
  StorageManager storageManager = createStorageManager(localNode, metricRegistry, null);
  storageManager.start();
  // test add store that already exists, which should fail
  assertFalse("Add store which is already existing should fail", storageManager.addBlobStore(localReplicas.get(0)));
  // test add store onto a new disk, which should succeed
  assertTrue("Add new store should succeed", storageManager.addBlobStore(newPartition1.getReplicaIds().get(0)));
  assertNotNull("The store shouldn't be null because new store is successfully added",
      storageManager.getStore(newPartition1, false));
  // test add store whose diskManager is not running, which should fail
  PartitionId newPartition2 =
      new MockPartitionId(11L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), 0);
  storageManager.getDiskManager(localReplicas.get(0).getPartitionId()).shutdown();
  assertFalse("Add store onto the DiskManager which is not running should fail",
      storageManager.addBlobStore(newPartition2.getReplicaIds().get(0)));
  storageManager.getDiskManager(localReplicas.get(0).getPartitionId()).start();
  // test replica addition can correctly handle existing dir (should delete it and create a new one)
  // To verify the directory has been recreated, we purposely put a test file in previous dir.
  PartitionId newPartition3 =
      new MockPartitionId(12L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), 0);
  ReplicaId replicaToAdd = newPartition3.getReplicaIds().get(0);
  File previousDir = new File(replicaToAdd.getReplicaPath());
  File testFile = new File(previousDir, "testFile");
  MockClusterMap.deleteFileOrDirectory(previousDir);
  assertTrue("Cannot create dir for " + replicaToAdd.getReplicaPath(), previousDir.mkdir());
  assertTrue("Cannot create test file within previous dir", testFile.createNewFile());
  assertTrue("Adding new store should succeed", storageManager.addBlobStore(replicaToAdd));
  assertFalse("Test file should not exist", testFile.exists());
  assertNotNull("Store associated new added replica should not be null",
      storageManager.getStore(newPartition3, false));
  shutdownAndAssertStoresInaccessible(storageManager, localReplicas);
  // test add store but fail to add segment requirements to DiskSpaceAllocator. (This is simulated by inducing
  // addRequiredSegments failure to make store inaccessible)
  List<String> mountPaths = localNode.getMountPaths();
  String diskToFail = mountPaths.get(0);
  File reservePoolDir = new File(diskToFail, diskManagerConfig.diskManagerReserveFileDirName);
  File storeReserveDir = new File(reservePoolDir, DiskSpaceAllocator.STORE_DIR_PREFIX + newPartition2.toString());
  StorageManager storageManager2 = createStorageManager(localNode, new MetricRegistry(), null);
  storageManager2.start();
  Utils.deleteFileOrDirectory(storeReserveDir);
  assertTrue("File creation should succeed", storeReserveDir.createNewFile());

  assertFalse("Add store should fail if store couldn't start due to initializePool failure",
      storageManager2.addBlobStore(newPartition2.getReplicaIds().get(0)));
  assertNull("New store shouldn't be in in-memory data structure", storageManager2.getStore(newPartition2, false));
  shutdownAndAssertStoresInaccessible(storageManager2, localReplicas);
}
 
源代码19 项目: picard   文件: MergeBamAlignmentTest.java
@Test
public void testShortFragmentHardClipping() throws IOException {
    final File output = File.createTempFile("testShortFragmentClipping", ".sam");
    output.deleteOnExit();
    final File alignedSam = new File(TEST_DATA_DIR, "hardclip.aligned.sam");
    final File unmappedSam = new File(TEST_DATA_DIR, "hardclip.unmapped.sam");
    final File ref = new File(TEST_DATA_DIR, "cliptest.fasta");

    final List<String> args = Arrays.asList(
            "UNMAPPED_BAM=" + unmappedSam.getAbsolutePath(),
            "ALIGNED_BAM=" + alignedSam.getAbsolutePath(),
            "OUTPUT=" + output.getAbsolutePath(),
            "REFERENCE_SEQUENCE=" + ref.getAbsolutePath(),
            "HARD_CLIP_OVERLAPPING_READS=true"
            );

    Assert.assertEquals(runPicardCommandLine(args), 0);

    final SamReader result = SamReaderFactory.makeDefault().open(output);
    final Map<String, SAMRecord> firstReadEncountered = new HashMap<String, SAMRecord>();
    for (final SAMRecord rec : result) {
        final SAMRecord otherEnd = firstReadEncountered.get(rec.getReadName());
        if (otherEnd == null) {
            firstReadEncountered.put(rec.getReadName(), rec);
        } else {
            final int fragmentStart = Math.min(rec.getAlignmentStart(), otherEnd.getAlignmentStart());
            final int fragmentEnd = Math.max(rec.getAlignmentEnd(), otherEnd.getAlignmentEnd());
            final String[] readNameFields = rec.getReadName().split(":");
            // Read name of each pair includes the expected fragment start and fragment end positions.
            final int expectedFragmentStart = Integer.parseInt(readNameFields[1]);
            final int expectedFragmentEnd = Integer.parseInt(readNameFields[2]);
            Assert.assertEquals(fragmentStart, expectedFragmentStart, rec.getReadName());
            Assert.assertEquals(fragmentEnd, expectedFragmentEnd, rec.getReadName());
            if (readNameFields[0].equals("FR_clip")) {
                Assert.assertEquals(rec.getCigarString(), rec.getReadNegativeStrandFlag()? "20H56M" : "56M20H");
                Assert.assertEquals(otherEnd.getCigarString(), otherEnd.getReadNegativeStrandFlag()? "20H56M" : "56M20H");

                if (!rec.getReadNegativeStrandFlag()) {
                    Assert.assertEquals(rec.getAttribute("XB"), "AGATCGGAAGAGCACACGTC");
                    Assert.assertEquals(rec.getAttribute("XQ"), "BBBBB?BBB?<?A?<7<<=9");
                } else {
                    Assert.assertEquals(rec.getAttribute("XB"), "AGATCGGAAGAGCGTCGTGT");
                    Assert.assertEquals(rec.getAttribute("XQ"), "[email protected]=CC:CCD");
                }
            } else {
                Assert.assertEquals(rec.getCigarString(), "76M");
                Assert.assertEquals(otherEnd.getCigarString(), "76M");
            }
        }
    }
}
 
源代码20 项目: olat   文件: ZipUtilITCase.java
/**
 * creates and deletes file, just for purpose of getting an temporary file name.
 * 
 * @param prefix
 * @return
 * @throws IOException
 */
private File getTempFileName(String prefix) throws IOException {
    File tempFile = File.createTempFile(prefix, "output");
    delete(tempFile);
    return tempFile;
}