java.io.FileOutputStream

Here are the examples of the java api class java.io.FileOutputStream taken from open source projects.

1. TestSystemMetrics#setUp()

View license
@Before
public void setUp() throws Exception {
    testPropertyFile = new Path(CommonTestingUtil.getTestDir(), System.currentTimeMillis() + ".properties");
    metricsOutputFile = new Path(CommonTestingUtil.getTestDir(), System.currentTimeMillis() + ".out");
    FileOutputStream out = new FileOutputStream(testPropertyFile.toUri().getPath());
    out.write("reporter.null=org.apache.tajo.util.metrics.reporter.NullReporter\n".getBytes());
    out.write("reporter.file=org.apache.tajo.util.metrics.reporter.MetricsFileScheduledReporter\n".getBytes());
    out.write("reporter.console=org.apache.tajo.util.metrics.reporter.MetricsConsoleScheduledReporter\n".getBytes());
    out.write("test-file-group.reporters=file\n".getBytes());
    out.write("test-console-group.reporters=console\n".getBytes());
    out.write("test-find-console-group.reporters=console,file\n".getBytes());
    out.write(("test-file-group.file.filename=" + metricsOutputFile.toUri().getPath() + "\n").getBytes());
    out.write("test-file-group.file.period=5\n".getBytes());
}

2. ScanStreamDelayTest#setUp()

Project: camel
Source File: ScanStreamDelayTest.java
View license
@Override
@Before
public void setUp() throws Exception {
    deleteDirectory("target/stream");
    createDirectory("target/stream");
    file = new File("target/stream/scanstreamdelayfile.txt");
    file.createNewFile();
    FileOutputStream fos = new FileOutputStream(file);
    fos.write("Hello\n".getBytes());
    fos.write("World\n".getBytes());
    fos.write("Hello\n".getBytes());
    fos.write("World\n".getBytes());
    fos.write("Hello\n".getBytes());
    fos.write("World\n".getBytes());
    fos.close();
    super.setUp();
}

3. SaslAuthenticatedTest#createJaasFile()

Project: zkclient
Source File: SaslAuthenticatedTest.java
View license
private String createJaasFile() throws IOException {
    File jaasFile = _temporaryFolder.newFile("jaas.conf");
    FileOutputStream jaasOutputStream = new java.io.FileOutputStream(jaasFile);
    jaasOutputStream.write(String.format("%s {\n\t%s required\n", _zkServerContextName, _zkModule).getBytes());
    jaasOutputStream.write(String.format("\tuser_super=\"%s\"\n", _userSuperPasswd).getBytes());
    jaasOutputStream.write(String.format("\tuser_%s=\"%s\";\n};\n\n", _userServerSide, _userServerSidePasswd).getBytes());
    jaasOutputStream.write(String.format("%s {\n\t%s required\n", _zkClientContextName, _zkModule).getBytes());
    jaasOutputStream.write(String.format("\tusername=\"%s\"\n", _userClientSide).getBytes());
    jaasOutputStream.write(String.format("\tpassword=\"%s\";\n};", _userClientSidePasswd).getBytes());
    jaasOutputStream.close();
    return jaasFile.getAbsolutePath();
}

4. MediaTest#testAdd()

Project: Anki-Android
Source File: MediaTest.java
View license
public void testAdd() throws IOException {
    // open new empty collection
    Collection d = Shared.getEmptyCol(getContext());
    File dir = Shared.getTestDir(getContext());
    BackupManager.removeDir(dir);
    dir.mkdirs();
    File path = new File(dir, "foo.jpg");
    FileOutputStream os;
    os = new FileOutputStream(path, false);
    os.write("hello".getBytes());
    os.close();
    // new file, should preserve name
    String r = d.getMedia().addFile(path);
    assertEquals("foo.jpg", r);
    // adding the same file again should not create a duplicate
    assertEquals("foo.jpg", d.getMedia().addFile(path));
    // but if it has a different md5, it should
    os = new FileOutputStream(path, false);
    os.write("world".getBytes());
    os.close();
    assertEquals("foo (1).jpg", d.getMedia().addFile(path));
}

5. MarkerFileExclusiveReadLockStrategyTest#writeFiles()

View license
private void writeFiles() throws Exception {
    LOG.debug("Writing files...");
    FileOutputStream fos = new FileOutputStream("target/marker/in/file1.dat");
    FileOutputStream fos2 = new FileOutputStream("target/marker/in/file2.dat");
    for (int i = 0; i < 20; i++) {
        fos.write(("Line " + i + LS).getBytes());
        fos2.write(("Line " + i + LS).getBytes());
        LOG.debug("Writing line " + i);
    }
    fos.flush();
    fos.close();
    fos2.flush();
    fos2.close();
}

6. TestTailSource#testFileOutputStream()

Project: flume
Source File: TestTailSource.java
View license
/**
   * This just shows that file output stream truncates existing files
   * 
   * @throws IOException
   */
@Test
public void testFileOutputStream() throws IOException {
    File tmp = FileUtil.createTempFile("tmp-", ".tmp");
    FileOutputStream f = new FileOutputStream(tmp);
    f.write("0123456789".getBytes());
    f.close();
    assertEquals(10, tmp.length());
    f = new FileOutputStream(tmp);
    f.write("01234".getBytes());
    f.close();
    assertEquals(5, tmp.length());
}

7. XMWriter#writeXMI()

Project: XM-File-Format
Source File: XMWriter.java
View license
/*
	 * takes image data and writes out an XMI format file to destination
	 * 
	 * @param image the image data to write
	 * @param destination the output destination to write to
	 * 
	 */
public static void writeXMI(Image image, File destination) throws IOException {
    destination.createNewFile();
    final FileOutputStream fos = new FileOutputStream(destination);
    fos.write(image.hasTransparency() ? 0b1 : 0b0);
    fos.write(new byte[] { (byte) ((image.getWidth() >>> 0) & 0xFF), (byte) ((image.getWidth() >>> 8) & 0xFF), (byte) ((image.getHeight() >>> 0) & 0xFF), (byte) ((image.getHeight() >>> 8) & 0xFF) });
    fos.write(image.getPixels());
    fos.flush();
    fos.close();
}

8. IntegrationTest#testEncryptedSignedOutputToFile()

Project: Resteasy
Source File: IntegrationTest.java
View license
@Test
public void testEncryptedSignedOutputToFile() throws Exception {
    ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/smime/encrypted/signed"));
    ClientResponse<String> res = request.get(String.class);
    MediaType contentType = MediaType.valueOf(res.getResponseHeaders().getFirst("Content-Type"));
    System.out.println(contentType);
    System.out.println();
    System.out.println(res.getEntity());
    FileOutputStream os = new FileOutputStream("target/python_encrypted_signed.txt");
    os.write("Content-Type: ".getBytes());
    os.write(contentType.toString().getBytes());
    os.write("\r\n".getBytes());
    os.write(res.getEntity().getBytes());
    os.close();
}

9. CreateFiles#main()

Project: openjdk
Source File: CreateFiles.java
View license
public static void main(String[] args) throws Exception {
    File f;
    FileOutputStream fos;
    String name = "€";
    f = new File(name + ".java");
    fos = new FileOutputStream(f);
    output(fos, "import java.lang.instrument.Instrumentation;");
    output(fos, "public class " + name + " {");
    output(fos, "    public static void premain(String ops, Instrumentation ins) {");
    output(fos, "        System.out.println(\"premain running\"); ");
    output(fos, "    }");
    output(fos, "}");
    fos.close();
    f = new File("agent.mf");
    fos = new FileOutputStream(f);
    output(fos, "Manifest-Version: 1.0");
    output(fos, "Premain-Class: " + name);
    output(fos, "");
    fos.close();
}

10. CreateFiles#main()

Project: jdk7u-jdk
Source File: CreateFiles.java
View license
public static void main(String[] args) throws Exception {
    File f;
    FileOutputStream fos;
    String name = "€";
    f = new File(name + ".java");
    fos = new FileOutputStream(f);
    output(fos, "import java.lang.instrument.Instrumentation;");
    output(fos, "public class " + name + " {");
    output(fos, "    public static void premain(String ops, Instrumentation ins) {");
    output(fos, "        System.out.println(\"premain running\"); ");
    output(fos, "    }");
    output(fos, "}");
    fos.close();
    f = new File("agent.mf");
    fos = new FileOutputStream(f);
    output(fos, "Manifest-Version: 1.0");
    output(fos, "Premain-Class: " + name);
    output(fos, "");
    fos.close();
}

11. ReportIncidentRoutesTest#setupFreePort()

Project: camel
Source File: ReportIncidentRoutesTest.java
View license
@BeforeClass
public static void setupFreePort() throws Exception {
    // find a free port number, and write that in the custom.properties file
    // which we will use for the unit tests, to avoid port number in use problems
    int port = AvailablePortFinder.getNextAvailable();
    String s = "proxy.port=" + port;
    int port2 = AvailablePortFinder.getNextAvailable();
    String s2 = "real.port=" + port2;
    File custom = new File("target/custom.properties");
    FileOutputStream fos = new FileOutputStream(custom);
    fos.write(s.getBytes());
    fos.write("\n".getBytes());
    fos.write(s2.getBytes());
    fos.close();
    url = "http://localhost:" + port + "/camel-example-cxf-proxy/webservices/incident";
}

12. XMWriter#writeXMM()

Project: XM-File-Format
Source File: XMWriter.java
View license
/*
	 * takes multiple image data and writes out an XMM format file to destination
	 * 
	 * @param images the images data to write
	 * @param destination the output destination
	 * 
	 */
public static void writeXMM(Image[] images, File destination) throws IOException {
    destination.createNewFile();
    final FileOutputStream fos = new FileOutputStream(destination);
    boolean transparency = false;
    for (final Image img : images) if ((transparency = img.hasTransparency()))
        break;
    fos.write(transparency ? 0b1 : 0b0);
    fos.write(images.length);
    for (final Image img : images) {
        fos.write(intShortToByte(img.getWidth()));
        fos.write(intShortToByte(img.getHeight()));
    }
    for (final Image img : images) {
        fos.write(img.hasTransparency() ? 0b1 : 0b0);
        fos.write(img.getPixels());
    }
    fos.flush();
    fos.close();
}

13. SedaFileIdempotentIssueTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    deleteDirectory("target/inbox");
    createDirectory("target/inbox");
    // create file without using Camel
    File file = new File("target/inbox/hello.txt");
    FileOutputStream fos = new FileOutputStream(file, true);
    fos.write("Hello World".getBytes());
    fos.flush();
    fos.close();
    super.setUp();
}

14. FileConsumerIdempotentLoadStoreTest#setUp()

View license
@SuppressWarnings("unchecked")
@Override
protected void setUp() throws Exception {
    deleteDirectory("target/fileidempotent");
    createDirectory("target/fileidempotent");
    File file = new File("target/fileidempotent/.filestore.dat");
    FileOutputStream fos = new FileOutputStream(file);
    // insert existing name to the file repo, so we should skip this file
    String name = FileUtil.normalizePath(new File("target/fileidempotent/report.txt").getAbsolutePath());
    fos.write(name.getBytes());
    fos.write(LS.getBytes());
    fos.close();
    super.setUp();
    // add a file to the repo
    repo = context.getRegistry().lookupByNameAndType("fileStore", IdempotentRepository.class);
}

15. ResetTest#testResetHard()

Project: che
Source File: ResetTest.java
View license
@Test(dataProvider = "GitConnectionFactory", dataProviderClass = org.eclipse.che.git.impl.GitConnectionFactoryProvider.class)
public void testResetHard(GitConnectionFactory connectionFactory) throws Exception {
    //given
    GitConnection connection = connectToGitRepositoryWithContent(connectionFactory, repository);
    File aaa = addFile(connection, "aaa", "aaa\n");
    FileOutputStream fos = new FileOutputStream(new File(connection.getWorkingDir(), "README.txt"));
    fos.write("MODIFIED\n".getBytes());
    fos.flush();
    fos.close();
    String initMessage = connection.log(newDto(LogRequest.class)).getCommits().get(0).getMessage();
    connection.add(newDto(AddRequest.class).withFilepattern(new ArrayList<>(Arrays.asList("."))));
    connection.commit(newDto(CommitRequest.class).withMessage("add file"));
    //when
    ResetRequest resetRequest = newDto(ResetRequest.class).withCommit("HEAD^");
    resetRequest.setType(ResetRequest.ResetType.HARD);
    connection.reset(resetRequest);
    //then
    assertEquals(connection.log(newDto(LogRequest.class)).getCommits().get(0).getMessage(), initMessage);
    assertFalse(aaa.exists());
    assertTrue(connection.status(StatusFormat.SHORT).isClean());
    assertEquals(CONTENT, Files.toString(new File(connection.getWorkingDir(), "README.txt"), Charsets.UTF_8));
}

16. ResetTest#testResetSoft()

Project: che
Source File: ResetTest.java
View license
@Test(dataProvider = "GitConnectionFactory", dataProviderClass = org.eclipse.che.git.impl.GitConnectionFactoryProvider.class)
public void testResetSoft(GitConnectionFactory connectionFactory) throws Exception {
    //given
    GitConnection connection = connectToGitRepositoryWithContent(connectionFactory, repository);
    File aaa = addFile(connection, "aaa", "aaa\n");
    FileOutputStream fos = new FileOutputStream(new File(connection.getWorkingDir(), "README.txt"));
    fos.write("MODIFIED\n".getBytes());
    fos.flush();
    fos.close();
    String initMessage = connection.log(newDto(LogRequest.class)).getCommits().get(0).getMessage();
    connection.add(newDto(AddRequest.class).withFilepattern(new ArrayList<>(Arrays.asList("."))));
    connection.commit(newDto(CommitRequest.class).withMessage("add file"));
    //when
    ResetRequest resetRequest = newDto(ResetRequest.class).withCommit("HEAD^");
    resetRequest.setType(ResetRequest.ResetType.SOFT);
    connection.reset(resetRequest);
    //then
    assertEquals(connection.log(newDto(LogRequest.class)).getCommits().get(0).getMessage(), initMessage);
    assertTrue(aaa.exists());
    assertEquals(connection.status(StatusFormat.SHORT).getAdded().get(0), "aaa");
    assertEquals(connection.status(StatusFormat.SHORT).getChanged().get(0), "README.txt");
    assertEquals(Files.toString(new File(connection.getWorkingDir(), "README.txt"), Charsets.UTF_8), "MODIFIED\n");
}

17. ResetTest#testResetMixed()

Project: che
Source File: ResetTest.java
View license
@Test(dataProvider = "GitConnectionFactory", dataProviderClass = org.eclipse.che.git.impl.GitConnectionFactoryProvider.class)
public void testResetMixed(GitConnectionFactory connectionFactory) throws Exception {
    //given
    GitConnection connection = connectToGitRepositoryWithContent(connectionFactory, repository);
    File aaa = addFile(connection, "aaa", "aaa\n");
    FileOutputStream fos = new FileOutputStream(new File(connection.getWorkingDir(), "README.txt"));
    fos.write("MODIFIED\n".getBytes());
    fos.flush();
    fos.close();
    String initMessage = connection.log(newDto(LogRequest.class)).getCommits().get(0).getMessage();
    connection.add(newDto(AddRequest.class).withFilepattern(new ArrayList<>(Arrays.asList("."))));
    connection.commit(newDto(CommitRequest.class).withMessage("add file"));
    //when
    ResetRequest resetRequest = newDto(ResetRequest.class).withCommit("HEAD^");
    resetRequest.setType(ResetRequest.ResetType.MIXED);
    connection.reset(resetRequest);
    //then
    assertEquals(connection.log(newDto(LogRequest.class)).getCommits().get(0).getMessage(), initMessage);
    assertTrue(aaa.exists());
    assertEquals(connection.status(StatusFormat.SHORT).getUntracked().get(0), "aaa");
    assertEquals(connection.status(StatusFormat.SHORT).getModified().get(0), "README.txt");
    assertEquals(Files.toString(new File(connection.getWorkingDir(), "README.txt"), Charsets.UTF_8), "MODIFIED\n");
}

18. TestHelpers#GenerateFileData()

Project: azure-sdk-for-java
Source File: TestHelpers.java
View license
/**
     * Generates some random data and writes it out to a temp file and to an in-memory array
     *
     * @param contents The array to write random data to (the length of this array will be the size of the file).
     * @return The path of the file that will be created.
     * @throws IOException
     */
static String GenerateFileData(byte[] contents) throws IOException {
    File filePath = File.createTempFile("adlUploader", "test.data");
    Random rnd = new Random(0);
    rnd.nextBytes(contents);
    if (filePath.exists()) {
        filePath.delete();
    }
    FileOutputStream writer = new FileOutputStream(filePath);
    writer.write(contents);
    writer.flush();
    writer.close();
    return filePath.toString();
}

19. AvlTreePerfTest#testAVLTreeSerializationPerf()

View license
@Test
@Ignore
public void testAVLTreeSerializationPerf() throws Exception {
    for (int i = 0; i < numKeys; i++) {
        tree.insert(i);
    }
    FileOutputStream fout = new FileOutputStream(treeSerialFile);
    start = System.nanoTime();
    fout.write(treeMarshaller.serialize(tree));
    fout.flush();
    fout.close();
    end = System.nanoTime();
    System.out.println("total time taken for serializing AVLTree ->" + getTime(start, end));
}

20. ApplicationPropertiesTest#testConfigLocation()

View license
@Test
public void testConfigLocation() throws Exception {
    File target = new File("target");
    if (!target.exists()) {
        target = new File("common/target");
    }
    FileOutputStream out = new FileOutputStream(new File(target, "config.properties"));
    out.write("*.domain=unittest\n".getBytes());
    out.write("unittest.test=hello world\n".getBytes());
    out.close();
    ApplicationProperties configLocation = new ConfigLocation();
    configLocation.loadProperties("config.properties", target.getAbsolutePath());
    Assert.assertEquals(configLocation.getDomain(), "unittest");
    Assert.assertEquals(configLocation.get("test"), "hello world");
}

21. Context#saveArduBlockFile()

Project: ardublock
Source File: Context.java
View license
public void saveArduBlockFile(File saveFile, String saveString) throws IOException {
    if (!saveFile.exists()) {
        saveFile.createNewFile();
    }
    FileOutputStream fos = new FileOutputStream(saveFile, false);
    fos.write(saveString.getBytes("UTF8"));
    fos.flush();
    fos.close();
    didSave();
}

22. JGitUtilsTest#testZip()

Project: gitblit
Source File: JGitUtilsTest.java
View license
@Test
public void testZip() throws Exception {
    assertFalse(CompressionUtils.zip(null, null, null, null, null));
    Repository repository = GitBlitSuite.getHelloworldRepository();
    File zipFileA = new File(GitBlitSuite.REPOSITORIES, "helloworld.zip");
    FileOutputStream fosA = new FileOutputStream(zipFileA);
    boolean successA = CompressionUtils.zip(repository, null, null, Constants.HEAD, fosA);
    fosA.close();
    File zipFileB = new File(GitBlitSuite.REPOSITORIES, "helloworld-java.zip");
    FileOutputStream fosB = new FileOutputStream(zipFileB);
    boolean successB = CompressionUtils.zip(repository, null, "java.java", Constants.HEAD, fosB);
    fosB.close();
    repository.close();
    assertTrue("Failed to generate zip file!", successA);
    assertTrue(zipFileA.length() > 0);
    zipFileA.delete();
    assertTrue("Failed to generate zip file!", successB);
    assertTrue(zipFileB.length() > 0);
    zipFileB.delete();
}

23. SerializableTileTest#testLoadTileValidHeaderNoData()

View license
@Test
public void testLoadTileValidHeaderNoData() throws IOException {
    // This is a file with a valid header, but no actual data
    File temp = File.createTempFile("temp", ".txt");
    FileOutputStream fos = new FileOutputStream(temp);
    byte[] tileData = { (byte) 0xde, (byte) 0xca, (byte) 0xfb, (byte) 0xad };
    fos.write(tileData);
    fos.flush();
    fos.close();
    assertTrue(temp.exists());
    SerializableTile newTile = new SerializableTile(temp);
    // Invalid tiles should return 0 bytes
    assertEquals(0, newTile.getTileData().length);
    // Corrupt tiles should also be automatically wiped off the disk
    assertFalse(temp.exists());
}

24. TestStore#testByteMarkEmpty()

Project: PalDB
Source File: TestStore.java
View license
@Test
public void testByteMarkEmpty() throws IOException {
    FileOutputStream fos = new FileOutputStream(STORE_FILE);
    fos.write(12345);
    fos.write(FormatVersion.getPrefixBytes()[0]);
    fos.write(3456);
    StoreWriter writer = PalDB.createWriter(fos, new Configuration());
    writer.close();
    StoreReader reader = PalDB.createReader(STORE_FILE, new Configuration());
    Assert.assertEquals(reader.size(), 0);
    Assert.assertNull(reader.get(1, null));
    reader.close();
}

25. TestStore#testByteMarkOneKey()

Project: PalDB
Source File: TestStore.java
View license
@Test
public void testByteMarkOneKey() throws IOException {
    FileOutputStream fos = new FileOutputStream(STORE_FILE);
    fos.write(12345);
    fos.write(FormatVersion.getPrefixBytes()[0]);
    fos.write(3456);
    StoreWriter writer = PalDB.createWriter(fos, new Configuration());
    writer.put(1, "foo");
    writer.close();
    StoreReader reader = PalDB.createReader(STORE_FILE, new Configuration());
    Assert.assertEquals(reader.size(), 1);
    Assert.assertEquals(reader.get(1), "foo");
    reader.close();
}

26. DirPollOperationTest#testPause()

Project: jPOS
Source File: DirPollOperationTest.java
View license
@Test
public void testPause() throws Exception {
    dirPoll.setShouldArchive(false);
    dirPoll.pause();
    testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, "dodgyTestFile3.test"));
    FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile);
    fileOutputStream.write("test".getBytes());
    fileOutputStream.flush();
    fileOutputStream.close();
    assertThat(testIncomingFile.exists(), is(true));
    // Sleep for enough time for dirpoll to pick up the file, if it wasn't paused
    Thread.sleep(DIRPOLL_CHECK_INTERVAL);
    assertThat(testIncomingFile.exists(), is(true));
    assertThat(dirPoll.isPaused(), is(true));
    dirPoll.unpause();
    waitForFileProcessed();
    assertThat(testIncomingFile.exists(), is(false));
}

27. Cluster#writeClusters()

Project: LIRE
Source File: Cluster.java
View license
public static void writeClusters(Cluster[] clusters, String path) throws IOException {
    File file = new File(path);
    if (file.exists()) {
        System.out.println("File " + path + " already exists and will be overwritten!!");
    }
    FileOutputStream fout = new FileOutputStream(file);
    fout.write(SerializationUtils.toBytes(clusters.length));
    fout.write(SerializationUtils.toBytes((clusters[0].getMean()).length));
    for (Cluster cluster : clusters) {
        fout.write(cluster.getByteRepresentation());
    }
    fout.close();
}

28. SerializedLayoutTest#testSerialization()

View license
@Test
public void testSerialization() throws Exception {
    final SerializedLayout layout = SerializedLayout.createLayout();
    final Throwable throwable = new LoggingException("Test");
    final LogEvent event = //
    Log4jLogEvent.newBuilder().setLoggerName(//
    this.getClass().getName()).setLoggerFqcn(//
    "org.apache.logging.log4j.core.Logger").setLevel(//
    Level.INFO).setMessage(//
    new SimpleMessage("Hello, world!")).setThrown(//
    throwable).build();
    final byte[] result = layout.toByteArray(event);
    assertNotNull(result);
    final FileOutputStream fos = new FileOutputStream(DAT_PATH);
    fos.write(layout.getHeader());
    fos.write(result);
    fos.close();
}

29. FileChangedReadLockTest#writeSlowFile()

Project: camel
Source File: FileChangedReadLockTest.java
View license
private void writeSlowFile() throws Exception {
    LOG.debug("Writing slow file...");
    FileOutputStream fos = new FileOutputStream("target/changed/in/slowfile.dat");
    for (int i = 0; i < 20; i++) {
        fos.write(("Line " + i + LS).getBytes());
        LOG.debug("Writing line " + i);
        Thread.sleep(200);
    }
    fos.flush();
    fos.close();
    LOG.debug("Writing slow file DONE...");
}

30. AbstractDataImportHandlerTestCase#createFile()

View license
@SuppressForbidden(reason = "Needs currentTimeMillis to set modified time for a file")
public static File createFile(File tmpdir, String name, byte[] content, boolean changeModifiedTime) throws IOException {
    File file = new File(tmpdir.getAbsolutePath() + File.separator + name);
    file.deleteOnExit();
    FileOutputStream f = new FileOutputStream(file);
    f.write(content);
    f.close();
    if (changeModifiedTime)
        file.setLastModified(System.currentTimeMillis() - 3600000);
    return file;
}

31. AtomicFileOutputStreamTest#testAbortExistingFileAfterFlush()

View license
/**
     * Ensure the tmp file is cleaned up and dstFile is untouched when
     * aborting an existing file overwrite.
     */
@Test
public void testAbortExistingFileAfterFlush() throws IOException {
    FileOutputStream fos1 = new FileOutputStream(dstFile);
    fos1.write(TEST_STRING.getBytes());
    fos1.close();
    AtomicFileOutputStream fos2 = new AtomicFileOutputStream(dstFile);
    fos2.write(TEST_STRING_2.getBytes());
    fos2.flush();
    fos2.abort();
    // Should not have touched original file
    assertEquals(TEST_STRING, ClientBase.readFile(dstFile));
    assertEquals(1, testDir.list().length);
}

32. AtomicFileOutputStreamTest#testAbortExistingFile()

View license
/**
     * Ensure the tmp file is cleaned up and dstFile is untouched when
     * aborting an existing file overwrite.
     */
@Test
public void testAbortExistingFile() throws IOException {
    FileOutputStream fos1 = new FileOutputStream(dstFile);
    fos1.write(TEST_STRING.getBytes());
    fos1.close();
    AtomicFileOutputStream fos2 = new AtomicFileOutputStream(dstFile);
    fos2.abort();
    // Should not have touched original file
    assertEquals(TEST_STRING, ClientBase.readFile(dstFile));
    assertEquals(1, testDir.list().length);
}

33. AtomicFileOutputStreamTest#testFailToFlush()

View license
/**
     * Test case where the flush() fails at close time - make sure that we clean
     * up after ourselves and don't touch any existing file at the destination
     */
@Test
public void testFailToFlush() throws IOException {
    // Create a file at destination
    FileOutputStream fos = new FileOutputStream(dstFile);
    fos.write(TEST_STRING_2.getBytes());
    fos.close();
    OutputStream failingStream = createFailingStream();
    failingStream.write(TEST_STRING.getBytes());
    try {
        failingStream.close();
        fail("Close didn't throw exception");
    } catch (IOException ioe) {
    }
    // Should not have touched original file
    assertEquals(TEST_STRING_2, ClientBase.readFile(dstFile));
    assertEquals("Temporary file should have been cleaned up", dstFile.getName(), ClientBase.join(",", testDir.list()));
}

34. AlluxioInterpreterTest#copyFromLocalLargeTest()

View license
@Test
public void copyFromLocalLargeTest() throws IOException, AlluxioException {
    File testFile = new File(mLocalAlluxioCluster.getAlluxioHome() + "/testFile");
    testFile.createNewFile();
    FileOutputStream fos = new FileOutputStream(testFile);
    byte[] toWrite = BufferUtils.getIncreasingByteArray(SIZE_BYTES);
    fos.write(toWrite);
    fos.close();
    InterpreterResult output = alluxioInterpreter.interpret("copyFromLocal " + testFile.getAbsolutePath() + " /testFile", null);
    Assert.assertEquals("Copied " + testFile.getAbsolutePath() + " to /testFile\n\n", output.message());
    long fileLength = fs.getStatus(new AlluxioURI("/testFile")).getLength();
    Assert.assertEquals(SIZE_BYTES, fileLength);
    FileInStream fStream = fs.openFile(new AlluxioURI("/testFile"));
    byte[] read = new byte[SIZE_BYTES];
    fStream.read(read);
    Assert.assertTrue(BufferUtils.equalIncreasingByteArray(SIZE_BYTES, read));
}

35. XStreamTest#createTestFile()

Project: xstream
Source File: XStreamTest.java
View license
private File createTestFile() throws FileNotFoundException, IOException, UnsupportedEncodingException {
    String xml = "" + "<component>\n" + "  <host>host</host>\n" + "  <port>8000</port>\n" + "</component>";
    File dir = new File("target/test-data");
    dir.mkdirs();
    File file = new File(dir, "test.xml");
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(xml.getBytes("UTF-8"));
    fos.close();
    return file;
}

36. ImageUtils#saveImage()

Project: wakao-app
Source File: ImageUtils.java
View license
public static void saveImage(Context context, String fileName, Bitmap bitmap, int quality) throws IOException {
    if (bitmap == null || fileName == null || context == null)
        return;
    FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, quality, stream);
    byte[] bytes = stream.toByteArray();
    fos.write(bytes);
    fos.close();
}

37. TestExecNioSource#testLineModeLargeEventOverflow()

Project: flume
Source File: TestExecNioSource.java
View license
public void testLineModeLargeEventOverflow(int overflow) throws IOException, FlumeSpecException, InterruptedException {
    int max = (int) FlumeConfiguration.get().getEventMaxSizeBytes();
    File tmpdir = FileUtil.mktempdir();
    File tmp = new File(tmpdir, "flume-tmp");
    StringBuilder tooLarge = new StringBuilder();
    for (int i = 0; i < max + overflow; ++i) {
        tooLarge.append("X");
    }
    tooLarge.append("\n");
    FileOutputStream f = new FileOutputStream(tmp);
    f.write(tooLarge.toString().getBytes());
    f.close();
    EventSource source = new ExecNioSource.Builder().build("cat " + tmp.getCanonicalPath());
    source.open();
    Event e = source.next();
    assertNotNull(e);
    // check that event was truncated.
    assertEquals(max, e.getBody().length);
    source.close();
    FileUtil.rmr(tmpdir);
    // Check that the stdout reader closed correctly
    assertTrue(((ExecNioSource) source).readOut.signalDone.get());
}

38. ReplacingFileUpdateTest#testFileDiffer()

View license
@Test
public void testFileDiffer() throws Exception {
    update.doUpdate();
    FileOutputStream output = new FileOutputStream(sourceFile);
    output.write("hello".getBytes());
    output.close();
    assertTrue(update.shouldBeApplied());
    update.doUpdate();
    assertEquals("hello", FileUtil.getFileContent(destFile));
}

39. DirClassRepo#store()

Project: erjang
Source File: DirClassRepo.java
View license
/* (non-Javadoc)
	 * @see erjang.beam.ClassRepo#store(java.lang.String, byte[])
	 */
@Override
public void store(String internalName, byte[] data) throws IOException {
    File out = new File(dir, internalName + ".class");
    File out_dir = out.getParentFile();
    out_dir.mkdirs();
    FileOutputStream fo = new FileOutputStream(out);
    fo.write(data);
    fo.close();
}

40. HttpHandler#writeToDisk()

View license
private void writeToDisk(HttpEntity entity, String file) throws IllegalStateException, IOException /**
     * writes a HTTP entity to the specified filename and location on disk
     */
{
    //int i = 0;
    String FilePath = "/sdcard/" + file;
    InputStream in = entity.getContent();
    byte buff[] = new byte[1024];
    FileOutputStream out = new FileOutputStream(FilePath);
    do {
        int numread = in.read(buff);
        if (numread <= 0)
            break;
        out.write(buff, 0, numread);
    //i++;
    } while (true);
    out.flush();
    out.close();
}

41. FilesystemAlterationMonitorTestCase#writeFile()

View license
protected File writeFile(final String pName, final byte[] pData) throws Exception {
    final File file = new File(directory, pName);
    final File parent = file.getParentFile();
    if (!parent.mkdirs() && !parent.isDirectory()) {
        throw new IOException("could not create" + parent);
    }
    log.debug("writing file " + pName + " (" + pData.length + " bytes)");
    final FileOutputStream os = new FileOutputStream(file);
    os.write(pData);
    os.close();
    assertTrue(file.exists());
    assertTrue(file.isFile());
    return file;
}

42. AbstractTestCase#writeFile()

Project: commons-jci
Source File: AbstractTestCase.java
View license
protected File writeFile(final String pName, final byte[] pData) throws Exception {
    final File file = new File(directory, pName);
    final File parent = file.getParentFile();
    if (!parent.mkdirs() && !parent.isDirectory()) {
        throw new IOException("could not create" + parent);
    }
    log.debug("writing file " + pName + " (" + pData.length + " bytes)");
    final FileOutputStream os = new FileOutputStream(file);
    os.write(pData);
    os.close();
    assertTrue(file.exists());
    assertTrue(file.isFile());
    return file;
}

43. FileUtil#copy()

Project: cloudhopper-commons
Source File: FileUtil.java
View license
/**
     * Copy the source file to the target file while optionally permitting an
     * overwrite to occur in case the target file already exists.
     * @param sourceFile The source file to copy from
     * @param targetFile The target file to copy to
     * @return True if an overwrite occurred, otherwise false.
     * @throws FileAlreadyExistsException Thrown if the target file already
     *      exists and an overwrite is not permitted.  This exception is a
     *      subclass of IOException, so catching an IOException is enough if you
     *      don't care about this specific reason.
     * @throws IOException Thrown if an error during the copy
     */
public static boolean copy(File sourceFile, File targetFile, boolean overwrite) throws FileAlreadyExistsException, IOException {
    boolean overwriteOccurred = false;
    // check if the targetFile already exists
    if (targetFile.exists()) {
        // if overwrite is not allowed, throw an exception
        if (!overwrite) {
            throw new FileAlreadyExistsException("Target file " + targetFile + " already exists");
        } else {
            // set the flag that it occurred
            overwriteOccurred = true;
        }
    }
    // proceed with copy
    FileInputStream fis = new FileInputStream(sourceFile);
    FileOutputStream fos = new FileOutputStream(targetFile);
    fis.getChannel().transferTo(0, sourceFile.length(), fos.getChannel());
    fis.close();
    fos.flush();
    fos.close();
    return overwriteOccurred;
}

44. ZipCreationUtilTest#simple()

Project: clerezza
Source File: ZipCreationUtilTest.java
View license
@Test
public void simple() throws Exception {
    Hierarchy root = new Hierarchy();
    root.addChild("/foo/bar/test", "my testdata".getBytes());
    root.addChild("/foo/bar/test1", "another testdata".getBytes());
    root.addChild("/foo/something", "something else".getBytes());
    byte[] zipData = ZipCreationUtil.createZip(root);
    File tmpFile = File.createTempFile("test", "zip");
    FileOutputStream fout = new FileOutputStream(tmpFile);
    fout.write(zipData);
    fout.close();
    ZipFile zipFile = new ZipFile(tmpFile);
    Enumeration<? extends ZipEntry> entriesEnum = zipFile.entries();
    Set<ZipEntry> entries = new HashSet<ZipEntry>();
    while (entriesEnum.hasMoreElements()) {
        final ZipEntry nextElement = entriesEnum.nextElement();
        System.out.println(nextElement);
        entries.add(nextElement);
    }
    Assert.assertEquals(3, entries.size());
}

45. DeltaProcessingTest#testAddClass()

Project: che
Source File: DeltaProcessingTest.java
View license
@Test
public void testAddClass() throws Exception {
    File workspace = new File(BaseTest.class.getResource("/projects").getFile());
    ResourceChangedEvent event = new ResourceChangedEvent(workspace, new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.CREATED, "projects", "test", "/test/src/main/java/org/eclipse/che/test/NewClass.java", false));
    NameEnvironmentAnswer answer = project.newSearchableNameEnvironment(DefaultWorkingCopyOwner.PRIMARY).findType(CharOperation.splitOn('.', "org.eclipse.che.test.NewClass".toCharArray()));
    assertThat(answer).isNull();
    FileOutputStream outputStream = new FileOutputStream(new File(workspace, "/test/src/main/java/org/eclipse/che/test/NewClass.java"));
    outputStream.write("package org.eclipse.che.test;\n public class NewClass{}\n".getBytes());
    outputStream.close();
    JavaModelManager.getJavaModelManager().deltaState.resourceChanged(event);
    answer = project.newSearchableNameEnvironment(DefaultWorkingCopyOwner.PRIMARY).findType(CharOperation.splitOn('.', "org.eclipse.che.test.NewClass".toCharArray()));
    assertThat(answer).isNotNull();
}

46. SpringJmsClientServerTest#setupFreePort()

View license
@BeforeClass
public static void setupFreePort() throws Exception {
    // find a free port number, and write that in the custom.properties file
    // which we will use for the unit tests, to avoid port number in use problems
    int port = AvailablePortFinder.getNextAvailable();
    String bank1 = "tcp.port=" + port;
    File custom = new File("target/custom.properties");
    FileOutputStream fos = new FileOutputStream(custom);
    fos.write(bank1.getBytes());
    fos.close();
}

47. SpringJmsClientRemotingServerTest#setupFreePort()

View license
@BeforeClass
public static void setupFreePort() throws Exception {
    // find a free port number, and write that in the custom.properties file
    // which we will use for the unit tests, to avoid port number in use problems
    int port = AvailablePortFinder.getNextAvailable();
    String bank1 = "tcp.port=" + port;
    File custom = new File("target/custom.properties");
    FileOutputStream fos = new FileOutputStream(custom);
    fos.write(bank1.getBytes());
    fos.close();
    appCtx = new ClassPathXmlApplicationContext("/META-INF/spring/camel-server.xml", "camel-client-remoting.xml");
    appCtx.start();
}

48. RmiTest#setupFreePort()

Project: camel
Source File: RmiTest.java
View license
@BeforeClass
public static void setupFreePort() throws Exception {
    // find a free port number, and write that in the custom.properties file
    // which we will use for the unit tests, to avoid port number in use problems
    port = AvailablePortFinder.getNextAvailable();
    String s = "port=" + port;
    File custom = new File("target/custom.properties");
    FileOutputStream fos = new FileOutputStream(custom);
    fos.write(s.getBytes());
    fos.close();
}

49. FtpChangedReadLockTest#writeSlowFile()

Project: camel
Source File: FtpChangedReadLockTest.java
View license
private void writeSlowFile() throws Exception {
    LOG.debug("Writing slow file...");
    createDirectory(FTP_ROOT_DIR + "/changed");
    FileOutputStream fos = new FileOutputStream(FTP_ROOT_DIR + "/changed/slowfile.dat", true);
    for (int i = 0; i < 20; i++) {
        fos.write(("Line " + i + LS).getBytes());
        LOG.debug("Writing line " + i);
        Thread.sleep(200);
    }
    fos.flush();
    fos.close();
    LOG.debug("Writing slow file DONE...");
}

50. AbstractBoxTestSupport#tearDownAfterClass()

Project: camel
Source File: AbstractBoxTestSupport.java
View license
@AfterClass
public static void tearDownAfterClass() throws Exception {
    CamelTestSupport.tearDownAfterClass();
    // write the refresh token back to target/test-classes/test-options.properties
    final URL resource = AbstractBoxTestSupport.class.getResource(TEST_OPTIONS_PROPERTIES);
    final FileOutputStream out = new FileOutputStream(new File(resource.getPath()));
    propertyText = propertyText.replaceAll(REFRESH_TOKEN_PROPERTY + "=\\S*", REFRESH_TOKEN_PROPERTY + "=" + refreshToken);
    out.write(propertyText.getBytes("UTF-8"));
    out.close();
}

51. FileIdempotentConsumerLoadStoreTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    // delete file store before testing
    if (store.exists()) {
        store.delete();
    }
    // insert existing to store
    FileOutputStream fos = new FileOutputStream(store);
    fos.write("4\n".getBytes());
    fos.close();
    repo = FileIdempotentRepository.fileIdempotentRepository(store);
    super.setUp();
    startEndpoint = resolveMandatoryEndpoint("direct:start");
    resultEndpoint = getMockEndpoint("mock:result");
}

52. FileChangedReadLockMinAgeTest#writeSlowFile()

View license
private void writeSlowFile() throws Exception {
    LOG.debug("Writing slow file...");
    FileOutputStream fos = new FileOutputStream("target/changed/in/slowfile.dat");
    for (int i = 0; i < 20; i++) {
        fos.write(("Line " + i + LS).getBytes());
        LOG.debug("Writing line " + i);
        Thread.sleep(100);
    }
    fos.flush();
    fos.close();
    LOG.debug("Writing slow file DONE...");
}

53. FileProducerCharsetUTFtoUTFTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    // use utf-8 as original payload with 00e6 which is a danish ae letter
    utf = "ABCæ".getBytes("utf-8");
    deleteDirectory("target/charset");
    createDirectory("target/charset/input");
    log.debug("utf: {}", new String(utf, Charset.forName("utf-8")));
    for (byte b : utf) {
        log.debug("utf byte: {}", b);
    }
    // write the byte array to a file using plain API
    FileOutputStream fos = new FileOutputStream("target/charset/input/input.txt");
    fos.write(utf);
    fos.close();
    super.setUp();
}

54. FileProducerCharsetUTFOptimizedTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    // use utf-8 as original payload with 00e6 which is a danish ae letter
    utf = "ABCæ".getBytes("utf-8");
    deleteDirectory("target/charset");
    createDirectory("target/charset/input");
    log.debug("utf: {}", new String(utf, Charset.forName("utf-8")));
    for (byte b : utf) {
        log.debug("utf byte: {}", b);
    }
    // write the byte array to a file using plain API
    FileOutputStream fos = new FileOutputStream("target/charset/input/input.txt");
    fos.write(utf);
    fos.close();
    super.setUp();
}

55. XformObsEdit#saveComplexObs()

Project: buendia
Source File: XformObsEdit.java
View license
public static String saveComplexObs(String nodeName, String value, Element formNode) throws Exception {
    byte[] bytes = Base64.decode(value);
    String path = formNode.getAttributeValue(null, "name");
    path += File.separatorChar + nodeName;
    File file = OpenmrsUtil.getOutFile(XformsUtil.getXformsComplexObsDir(path), new Date(), Context.getAuthenticatedUser());
    FileOutputStream writter = new FileOutputStream(file);
    writter.write(bytes);
    writter.close();
    return file.getAbsolutePath();
}

56. AttachmentService#uploadFile()

Project: axis2-java
Source File: AttachmentService.java
View license
public String uploadFile(String name, String attchmentID) throws IOException {
    MessageContext msgCtx = MessageContext.getCurrentMessageContext();
    Attachments attachment = msgCtx.getAttachmentMap();
    DataHandler dataHandler = attachment.getDataHandler(attchmentID);
    File file = new File(name);
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    dataHandler.writeTo(fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();
    return "File saved succesfully.";
}

57. MTOMSampleSkeleton#attachment()

Project: axis2-java
Source File: MTOMSampleSkeleton.java
View license
/**
	 * Auto generated method signature
	 * 
	 * @param param0
	 * @throws Exception 
	 * 
	 */
public org.apache.ws.axis2.mtomsample.AttachmentResponse attachment(org.apache.ws.axis2.mtomsample.AttachmentRequest param0) throws Exception {
    AttachmentType attachmentRequest = param0.getAttachmentRequest();
    Base64Binary binaryData = attachmentRequest.getBinaryData();
    DataHandler dataHandler = binaryData.getBase64Binary();
    File file = new File(attachmentRequest.getFileName());
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    dataHandler.writeTo(fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();
    AttachmentResponse response = new AttachmentResponse();
    response.setAttachmentResponse("File saved succesfully.");
    return response;
}

58. Util#copyContentUriToFile()

Project: aws-sdk-android-samples
Source File: Util.java
View license
/**
     * Copies the data from the passed in Uri, to a new file for use with the
     * Transfer Service
     * 
     * @param context
     * @param uri
     * @return
     * @throws IOException
     */
public static File copyContentUriToFile(Context context, Uri uri) throws IOException {
    InputStream is = context.getContentResolver().openInputStream(uri);
    File copiedData = new File(context.getDir("SampleImagesDir", Context.MODE_PRIVATE), UUID.randomUUID().toString());
    copiedData.createNewFile();
    FileOutputStream fos = new FileOutputStream(copiedData);
    byte[] buf = new byte[2046];
    int read = -1;
    while ((read = is.read(buf)) != -1) {
        fos.write(buf, 0, read);
    }
    fos.flush();
    fos.close();
    return copiedData;
}

59. EAdaptJniTask#handleFile()

Project: appcan-android
Source File: EAdaptJniTask.java
View license
private void handleFile(AssetManager asset, String fileName) throws Exception {
    FileOutputStream outStream = new FileOutputStream(DeviceDirName + fileName);
    InputStream inStream = asset.open(fileName);
    byte[] temp = new byte[1024 * 8];
    int i = 0;
    while ((i = inStream.read(temp)) > 0) {
        outStream.write(temp, 0, i);
    }
    outStream.flush();
    inStream.close();
    outStream.close();
}

60. TestExtParser#setUp()

Project: anthelion
Source File: TestExtParser.java
View license
protected void setUp() throws ProtocolException, IOException {
    // prepare a temp file with expectedText as its content
    // This system property is defined in ./src/plugin/build-plugin.xml
    String path = System.getProperty("test.data");
    if (path != null) {
        File tempDir = new File(path);
        if (!tempDir.exists())
            tempDir.mkdir();
        tempFile = File.createTempFile("nutch.test.plugin.ExtParser.", ".txt", tempDir);
    } else {
        // otherwise in java.io.tmpdir
        tempFile = File.createTempFile("nutch.test.plugin.ExtParser.", ".txt");
    }
    urlString = tempFile.toURL().toString();
    FileOutputStream fos = new FileOutputStream(tempFile);
    fos.write(expectedText.getBytes());
    fos.close();
    // get nutch content
    Protocol protocol = new ProtocolFactory(NutchConfiguration.create()).getProtocol(urlString);
    content = protocol.getProtocolOutput(new Text(urlString), new CrawlDatum()).getContent();
    protocol = null;
}

61. SDUtil#saveFileToSDCard()

Project: AndroidStudyDemo
Source File: SDUtil.java
View license
/**
     * Write file to SD card
     *
     * @param filePath ????
     * @param filename ???
     * @param content  ??
     * @return ??????
     * @throws Exception
     */
public static boolean saveFileToSDCard(String filePath, String filename, String content) throws Exception {
    boolean flag = false;
    if (!checkSDCardAvailable())
        return flag;
    File dir = new File(filePath);
    if (!dir.exists()) {
        dir.mkdir();
    }
    File file = new File(filePath, filename);
    FileOutputStream outStream = new FileOutputStream(file);
    outStream.write(content.getBytes());
    outStream.close();
    flag = true;
    return flag;
}

62. CpeDescriptorSerialization_Test#testReadDescriptor2()

View license
/**
   * test to be sure, that first reading and then writing a discriptor produces the same file as the
   * original (new configuration file format).
   * 
   * @throws Exception -
   */
public void testReadDescriptor2() throws Exception {
    // input file
    File cpeDescFile = JUnitExtension.getFile("CpmTests/CpeAPITest/refConf2.xml");
    XMLInputSource in = new XMLInputSource(cpeDescFile);
    cpeDesc = UIMAFramework.getXMLParser().parseCpeDescription(in);
    // output file
    File outputFile = new File(this.testBaseDir, "outConf2.xml");
    // serialize input file to output file
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    cpeDesc.toXML(outStream);
    FileOutputStream fOut = new FileOutputStream(outputFile);
    fOut.write(outStream.toByteArray());
    fOut.close();
    equal(cpeDescFile, cpeDesc);
    outputFile.delete();
}

63. CpeDescriptorSerialization_Test#testReadDescriptor()

View license
/**
   * test to be sure, that first reading and then writing a discriptor produces the same file as the
   * original.(old configuration file format)
   * 
   * @throws Exception -
   */
public void testReadDescriptor() throws Exception {
    // input file
    File cpeDescFile = JUnitExtension.getFile("CpmTests/CpeAPITest/refConf.xml");
    XMLInputSource in = new XMLInputSource(cpeDescFile);
    cpeDesc = UIMAFramework.getXMLParser().parseCpeDescription(in);
    // output file
    File outputFile = new File(this.testBaseDir, "outConf.xml");
    // serialize input file to output file
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    cpeDesc.toXML(outStream);
    FileOutputStream fOut = new FileOutputStream(outputFile);
    fOut.write(outStream.toByteArray());
    fOut.close();
    // compare input and output
    equal(cpeDescFile, cpeDesc);
    outputFile.delete();
}

64. FileUtilTest#isEmpty_withFilledFile()

Project: uadetector
Source File: FileUtilTest.java
View license
@Test
public void isEmpty_withFilledFile() throws Exception {
    final File tempEmptyFile = File.createTempFile("testfile", ".tmp");
    tempEmptyFile.deleteOnExit();
    final FileOutputStream writer = new FileOutputStream(tempEmptyFile);
    writer.write("test".getBytes());
    writer.close();
    final boolean isEmpty = FileUtil.isEmpty(tempEmptyFile, CHARSET);
    PowerMock.verifyAll();
    assertThat(isEmpty).isFalse();
    tempEmptyFile.delete();
}

65. Railroads#processHtml()

Project: ThriftyPaxos
Source File: Railroads.java
View license
private void processHtml(String fileName) throws Exception {
    String source = "src/tools/org/h2/jcr/";
    String target = "docs/html/";
    byte[] s = BuildBase.readFile(new File(source + "stylesheet.css"));
    BuildBase.writeFile(new File(target + "stylesheet.css"), s);
    String inFile = source + fileName;
    String outFile = target + fileName;
    new File(outFile).getParentFile().mkdirs();
    FileOutputStream out = new FileOutputStream(outFile);
    FileInputStream in = new FileInputStream(inFile);
    byte[] bytes = IOUtils.readBytesAndClose(in, 0);
    if (fileName.endsWith(".html")) {
        String page = new String(bytes);
        page = PageParser.parse(page, session);
        bytes = page.getBytes();
    }
    out.write(bytes);
    out.close();
}

66. GenerateDoc#process()

Project: ThriftyPaxos
Source File: GenerateDoc.java
View license
private void process(String dir, String fileName) throws Exception {
    String inFile = inDir + "/" + dir + "/" + fileName;
    String outFile = outDir + "/" + dir + "/" + fileName;
    new File(outFile).getParentFile().mkdirs();
    FileOutputStream out = new FileOutputStream(outFile);
    FileInputStream in = new FileInputStream(inFile);
    byte[] bytes = IOUtils.readBytesAndClose(in, 0);
    if (fileName.endsWith(".html")) {
        String page = new String(bytes);
        page = PageParser.parse(page, session);
        bytes = page.getBytes();
    }
    out.write(bytes);
    out.close();
}

67. MainActivity#saveIndexHtml()

Project: task_1
Source File: MainActivity.java
View license
public void saveIndexHtml() throws IOException {
    String str = doc.html();
    InputStream is = new ByteArrayInputStream(str.getBytes());
    File file = new File(context.getFilesDir().getPath() + "//HTML", "index.html");
    FileOutputStream fos = new FileOutputStream(file);
    byte[] bytes = new byte[2048];
    int len = 0;
    while ((len = is.read(bytes)) != -1) {
        fos.write(bytes, 0, len);
    }
    fos.flush();
    fos.close();
    is.close();
}

68. ConnectionTest#copyToTemp()

Project: sqlite-jdbc
Source File: ConnectionTest.java
View license
public static File copyToTemp(String fileName) throws IOException {
    InputStream in = ConnectionTest.class.getResourceAsStream(fileName);
    File dir = new File("target");
    if (!dir.exists())
        dir.mkdirs();
    File tmp = File.createTempFile(fileName, "", new File("target"));
    tmp.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tmp);
    byte[] buf = new byte[8192];
    for (int readBytes = 0; (readBytes = in.read(buf)) != -1; ) {
        out.write(buf, 0, readBytes);
    }
    out.flush();
    out.close();
    in.close();
    return tmp;
}

69. PostServletImportTest#getTestFile()

Project: sling
Source File: PostServletImportTest.java
View license
private File getTestFile(InputStream inputStream) throws IOException {
    File tempFile = File.createTempFile("file-to-upload", null, new File("target"));
    FileOutputStream outputStream = new FileOutputStream(tempFile);
    //16k
    byte[] bbuf = new byte[16384];
    int len;
    while ((len = inputStream.read(bbuf)) != -1) {
        outputStream.write(bbuf, 0, len);
    }
    outputStream.flush();
    outputStream.close();
    return tempFile;
}

70. ExtractSounds#exportTo()

Project: settlers-remake
Source File: ExtractSounds.java
View license
/**
	 * Export data to a given wav file path.
	 * 
	 * @param data
	 * @param seqFile
	 * @throws IOException
	 */
private static void exportTo(short[] data, File seqFile) throws IOException {
    FileOutputStream os = new FileOutputStream(seqFile);
    os.write(new byte[] { 'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ', 0x10, 0, 0, 0, 1, 0, 2, 0, 0x22, (byte) 0x56, 0, 0, 0x10, (byte) 0xb1, 2, 0, 4, 0, 0x10, 0, 'd', 'a', 't', 'a' });
    for (short d : data) {
        os.write(d & 0xff);
        os.write((d / 256) & 0xff);
        os.write(d & 0xff);
        os.write((d / 256) & 0xff);
    }
    os.close();
}

71. TestServerConfiguration#testCorruptionOfPolicyFile()

Project: sentry
Source File: TestServerConfiguration.java
View license
/**
   * Test corruption of policy file
   */
@Test
public void testCorruptionOfPolicyFile() throws Exception {
    context = createContext(properties);
    File policyFile = context.getPolicyFile();
    FileOutputStream out = new FileOutputStream(policyFile);
    out.write("this is not valid".getBytes(Charsets.UTF_8));
    out.close();
    Connection connection = context.createConnection(ADMIN1);
    Statement statement = context.createStatement(connection);
    try {
        statement.execute("DROP TABLE IF EXISTS test CASCADE");
        statement.execute("create table test (a string)");
        Assert.fail("Expected SQLException");
    } catch (SQLException e) {
        context.verifyAuthzException(e);
    }
}

72. CmsSetupTestSimapi#writeFile()

View license
private File writeFile(String rfsName, byte[] content) throws IOException {
    File f = new File(rfsName);
    File p = f.getParentFile();
    if (!p.exists()) {
        // create parent folders
        p.mkdirs();
    }
    // write file contents
    FileOutputStream fs = new FileOutputStream(f);
    fs.write(content);
    fs.close();
    return f;
}

73. CmsExportHelper#writeFile2Rfs()

Project: opencms-core
Source File: CmsExportHelper.java
View license
/**
     * Writes a single OpenCms VFS file to the RFS export.<p>
     *
     * @param file the OpenCms VFS file to write
     * @param name the name of the file in the export
     *
     * @throws IOException in case of file access issues
     */
protected void writeFile2Rfs(CmsFile file, String name) throws IOException {
    String fileName = getRfsFileName(name);
    File rfsFile = new File(fileName);
    if (!rfsFile.getParentFile().exists()) {
        rfsFile.getParentFile().mkdirs();
    }
    rfsFile.createNewFile();
    FileOutputStream rfsFileOut = new FileOutputStream(rfsFile);
    rfsFileOut.write(file.getContents());
    rfsFileOut.close();
}

74. CmsVfsDiskCache#saveFile()

Project: opencms-core
Source File: CmsVfsDiskCache.java
View license
/**
     * Saves the given file content to a RFS file of the given name (full path).<p>
     *
     * If the required parent folders do not exists, they are also created.<p>
     *
     * @param rfsName the RFS name of the file to save the content in
     * @param content the content of the file to save
     *
     * @return a reference to the File that was saved
     *
     * @throws IOException in case of disk access errors
     */
public static File saveFile(String rfsName, byte[] content) throws IOException {
    File f = new File(rfsName);
    File p = f.getParentFile();
    if (!p.exists()) {
        // create parent folders
        p.mkdirs();
    }
    // write file contents
    FileOutputStream fs = new FileOutputStream(f);
    fs.write(content);
    fs.close();
    return f;
}

75. TimeCodeBoxTest#checkRealLifeBox()

Project: mp4parser
Source File: TimeCodeBoxTest.java
View license
@Test
public void checkRealLifeBox() throws IOException, DecoderException {
    File f = File.createTempFile("TimeCodeBoxTest", "checkRealLifeBox");
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(Hex.decodeHex(tcmd.toCharArray()));
    fos.close();
    IsoFile isoFile = new IsoFile(new FileInputStream(f).getChannel());
    TimeCodeBox tcmd = (TimeCodeBox) isoFile.getBoxes().get(0);
    System.err.println(tcmd);
    isoFile.close();
    f.delete();
}

76. ModelTester#writeReportToDisk()

Project: Metronome
Source File: ModelTester.java
View license
public static void writeReportToDisk(Evaluation eval, String fileLocation) throws IOException {
    // open files somewhere
    File yourFile = new File(fileLocation);
    if (!yourFile.exists()) {
        yourFile.createNewFile();
    }
    FileOutputStream oFile = new FileOutputStream(fileLocation, false);
    oFile.write(eval.stats().getBytes());
    oFile.close();
}

77. GCodeFile#save()

Project: Makelangelo
Source File: GCodeFile.java
View license
public void save(String filename) throws IOException {
    FileOutputStream out = new FileOutputStream(filename);
    String temp;
    for (int i = 0; i < getLinesTotal(); ++i) {
        temp = lines.get(i);
        if (!temp.endsWith(";") && !temp.endsWith(";\n")) {
            temp += ";";
        }
        if (!temp.endsWith("\n"))
            temp += "\n";
        out.write(temp.getBytes());
    }
    out.flush();
    out.close();
}

78. TestCopyCommandClusterSchemaEvolution#createDestination()

View license
@Override
public void createDestination() throws Exception {
    FileInputStream schemaIn = new FileInputStream(avsc);
    Schema original = new Schema.Parser().parse(schemaIn);
    schemaIn.close();
    Schema evolved = getEvolvedSchema(original);
    FileOutputStream schemaOut = new FileOutputStream(evolvedAvsc);
    schemaOut.write(evolved.toString(true).getBytes());
    schemaOut.close();
    List<String> createArgs = Lists.newArrayList("create", dest, "-s", evolvedAvsc, "-r", repoUri, "-d", "target/data");
    createArgs.addAll(getExtraCreateArgs());
    TestUtil.run(LoggerFactory.getLogger(this.getClass()), "delete", dest, "-r", repoUri, "-d", "target/data");
    TestUtil.run(LoggerFactory.getLogger(this.getClass()), createArgs.toArray(new String[createArgs.size()]));
    this.console = mock(Logger.class);
    this.command = new CopyCommand(console);
    command.setConf(new Configuration());
}

79. ImageBasedTests#writeBitmap()

View license
/**
     * Writes a bitmap to /mnt/shell/emulated/0/pixateTests/FailingBitmaps/
     * 
     * @param bitmap
     * @param imageId
     * @throws IOException
     */
private static void writeBitmap(Bitmap bitmap, String imageId) throws IOException {
    String path = Environment.getExternalStorageDirectory().getPath() + FAILING_BITMAPS_PATH;
    File outputDir = new File(path);
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    File file = new File(path, imageId + ".png");
    FileOutputStream out = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
    out.flush();
    out.close();
}

80. SignedTest#testPythonVerified()

Project: Resteasy
Source File: SignedTest.java
View license
@Test
public void testPythonVerified() throws Exception {
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    SignerInfoGenerator signer = new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").build("SHA1WITHRSA", privateKey, cert);
    gen.addSignerInfoGenerator(signer);
    MimeMultipart mp = gen.generate(createMsg());
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mp.writeTo(os);
    String contentType = mp.getContentType();
    contentType = contentType.replace("\r\n", "").replace("\t", " ");
    System.out.println(contentType);
    String s = new String(os.toByteArray());
    StringBuilder builder = new StringBuilder();
    builder.append("Content-Type: ").append(contentType).append("\r\n\r\n").append(s);
    String output = builder.toString();
    FileOutputStream fp = new FileOutputStream("target/smime_signed.txt");
    fp.write(output.getBytes());
    fp.close();
}

81. SuperCamera#saveToSDCard()

Project: rebot_joystick
Source File: SuperCamera.java
View license
/** ??????sdcard **/
public static String saveToSDCard(byte[] data) throws IOException {
    Date date = new Date();
    // ?????
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
    String filename = format.format(date) + ".jpeg";
    File fileFolder = new File(Environment.getExternalStorageDirectory() + "/demo");
    if (// ???????????????"finger"???
    !fileFolder.exists()) {
        fileFolder.mkdir();
    }
    File jpgFile = new File(fileFolder, filename);
    // ?????
    FileOutputStream outputStream = new FileOutputStream(jpgFile);
    // ??sd??
    outputStream.write(data);
    // ?????
    outputStream.close();
    String jpgFilePath = jpgFile.getAbsolutePath();
    return jpgFilePath;
}

82. RealmTests#incompatibleLockFile()

Project: realm-java
Source File: RealmTests.java
View license
@Test
public void incompatibleLockFile() throws IOException {
    // Replace .lock file with a corrupted one
    File lockFile = new File(realmConfig.getPath() + ".lock");
    assertTrue(lockFile.exists());
    FileOutputStream fooStream = new FileOutputStream(lockFile, false);
    fooStream.write("Boom".getBytes());
    fooStream.close();
    try {
        // This will try to open a second SharedGroup which should fail when the .lock file is corrupt
        DynamicRealm.getInstance(realm.getConfiguration());
        fail();
    } catch (RealmError expected) {
        assertTrue(expected.getMessage().contains("Info size doesn't match"));
    } finally {
        lockFile.delete();
    }
}

83. TerminologyUploaderProviderDstu3Test#testUploadSctLocalFile()

View license
@Test
public void testUploadSctLocalFile() throws Exception {
    byte[] packageBytes = createSctZip();
    File tempFile = File.createTempFile("tmp", ".zip");
    tempFile.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tempFile);
    fos.write(packageBytes);
    fos.close();
    //@formatter:off
    Parameters respParam = ourClient.operation().onServer().named("upload-external-code-system").withParameter(Parameters.class, "url", new UriType(IHapiTerminologyLoaderSvc.SCT_URL)).andParameter("localfile", new StringType(tempFile.getAbsolutePath())).execute();
    //@formatter:on
    String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
    ourLog.info(resp);
    assertThat(((IntegerType) respParam.getParameter().get(0).getValue()).getValue(), greaterThan(1));
}

84. TestNativeIO#testOpenWithCreate()

Project: hadoop-20
Source File: TestNativeIO.java
View license
@Test
public void testOpenWithCreate() throws Exception {
    LOG.info("Test creating a file with O_CREAT");
    FileDescriptor fd = NativeIO.open(new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT, 0700);
    assertNotNull(true);
    assertTrue(fd.valid());
    FileOutputStream fos = new FileOutputStream(fd);
    fos.write("foo".getBytes());
    fos.close();
    assertFalse(fd.valid());
    LOG.info("Test exclusive create");
    try {
        fd = NativeIO.open(new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(), NativeIO.O_WRONLY | NativeIO.O_CREAT | NativeIO.O_EXCL, 0700);
        fail("Was able to create existing file with O_EXCL");
    } catch (NativeIOException nioe) {
        LOG.info("Got expected exception for failed exclusive create", nioe);
        assertEquals(Errno.EEXIST, nioe.getErrno());
    }
}

85. TestAtomicFileOutputStream#testFailToFlush()

View license
/**
   * Test case where the flush() fails at close time - make sure
   * that we clean up after ourselves and don't touch any
   * existing file at the destination
   */
@Test
public void testFailToFlush() throws IOException {
    // Create a file at destination
    FileOutputStream fos = new FileOutputStream(DST_FILE);
    fos.write(TEST_STRING_2.getBytes());
    fos.close();
    OutputStream failingStream = createFailingStream();
    failingStream.write(TEST_STRING.getBytes());
    try {
        failingStream.close();
        fail("Close didn't throw exception");
    } catch (IOException ioe) {
    }
    // Should not have touched original file
    assertEquals(TEST_STRING_2, DFSTestUtil.readFile(DST_FILE));
    assertEquals("Temporary file should have been cleaned up", DST_FILE.getName(), Joiner.on(",").join(TEST_DIR.list()));
}

86. TestHTTPD#testSingleFileServer()

Project: h-store
Source File: TestHTTPD.java
View license
public void testSingleFileServer() throws IOException {
    File f = File.createTempFile("testSingleFileServer", ".jar");
    byte[] data = new byte[1000];
    data[777] = 31;
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(data);
    fos.close();
    SingleFileHTTPServer server = SingleFileHTTPServer.serveFile(f);
    String uri = server.m_uri;
    URL url = new URL(uri);
    InputStream is = url.openStream();
    byte[] data2 = new byte[1000];
    is.read(data2);
    assertTrue(data2[777] == data[777]);
    server.shutdown(true);
}

87. CommandLineTest#shouldNotLogPasswordsOnExceptionThrown()

Project: gocd
Source File: CommandLineTest.java
View license
@Test
@RunIf(value = OSChecker.class, arguments = OSChecker.LINUX)
public void shouldNotLogPasswordsOnExceptionThrown() throws IOException {
    File dir = FileUtil.createTempFolder();
    File file = new File(dir, "test.sh");
    FileOutputStream out = new FileOutputStream(file);
    out.write("echo $1 && exit 10".getBytes());
    out.close();
    CommandLine line = CommandLine.createCommandLine("/bin/sh").withArg(file.getAbsolutePath()).withArg(new PasswordArgument("secret"));
    try {
        line.runOrBomb(null);
    } catch (CommandLineException e) {
        assertThat(e.getMessage(), not(containsString("secret")));
    }
}

88. LSystem#retrieveFromAssets()

Project: LGame
Source File: LSystem.java
View license
private static void retrieveFromAssets(Activity activity, String filename) throws IOException {
    InputStream is = activity.getAssets().open(filename);
    File outFile = new File(activity.getFilesDir(), filename);
    makedirs(outFile);
    FileOutputStream fos = new FileOutputStream(outFile);
    byte[] buffer = new byte[2048];
    int length;
    while ((length = is.read(buffer)) > 0) {
        fos.write(buffer, 0, length);
    }
    fos.flush();
    fos.close();
    is.close();
}

89. Loon#retrieveFromAssets()

Project: LGame
Source File: Loon.java
View license
private static void retrieveFromAssets(Activity activity, String filename) throws IOException {
    InputStream is = activity.getAssets().open(filename);
    File outFile = new File(activity.getFilesDir(), filename);
    makedirs(outFile);
    FileOutputStream fos = new FileOutputStream(outFile);
    byte[] buffer = new byte[2048];
    int length;
    while ((length = is.read(buffer)) > 0) {
        fos.write(buffer, 0, length);
    }
    fos.flush();
    fos.close();
    is.close();
}

90. WGet#saveToFile()

Project: lenya
Source File: WGet.java
View license
/**
     *
     */
public void saveToFile(String filename, byte[] bytes) throws FileNotFoundException, IOException {
    File file = new File(filename);
    File parent = new File(file.getParent());
    if (!parent.exists()) {
        log.warn(".saveToFile(): Directory will be created: " + parent.getAbsolutePath());
        parent.mkdirs();
    }
    FileOutputStream out = new FileOutputStream(file.getAbsolutePath());
    out.write(bytes);
    out.close();
}

91. DirPollOperationTest#testCompressArchiveFile()

Project: jPOS
Source File: DirPollOperationTest.java
View license
@Test
public void testCompressArchiveFile() throws IOException, InterruptedException {
    String filename = "dodgyTestFile.test";
    dirPoll.setShouldArchive(true);
    dirPoll.setShouldCompressArchive(true);
    dirPoll.setArchiveDateFormat(DATE_FORMAT_STRING);
    dirPoll.setShouldTimestampArchive(false);
    testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, filename));
    FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile);
    fileOutputStream.write("test".getBytes());
    fileOutputStream.flush();
    assertThat(testIncomingFile.exists(), is(true));
    File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR));
    waitForFileProcessed();
    waitForNumFilesInDirOrTimeout(1, archiveDirectory, 5000);
    assertThat(archiveDirectory.listFiles().length, is(1));
    assertThat(archiveDirectory.listFiles()[0].getName(), is(testIncomingFile.getName() + ".zip"));
}

92. CrossRealm#xRealmAuth()

Project: jdk7u-jdk
Source File: CrossRealm.java
View license
static void xRealmAuth() throws Exception {
    Security.setProperty("auth.login.defaultCallbackHandler", "CrossRealm");
    System.setProperty("java.security.auth.login.config", "jaas-localkdc.conf");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    new File("jaas-localkdc.conf").deleteOnExit();
    FileOutputStream fos = new FileOutputStream("jaas-localkdc.conf");
    fos.write(("com.sun.security.jgss.krb5.initiate {\n" + "    com.sun.security.auth.module.Krb5LoginModule\n" + "    required\n" + "    principal=dummy\n" + "    doNotPrompt=false\n" + "    useTicketCache=false\n" + "    ;\n" + "};").getBytes());
    fos.close();
    GSSManager m = GSSManager.getInstance();
    m.createContext(m.createName("[email protected]", GSSName.NT_HOSTBASED_SERVICE), GSSUtil.GSS_KRB5_MECH_OID, null, GSSContext.DEFAULT_LIFETIME).initSecContext(new byte[0], 0, 0);
}

93. SimpleApplication#doMyAppStart()

Project: jdk7u-jdk
Source File: SimpleApplication.java
View license
// execute the application start protocol
public final void doMyAppStart(String[] args) throws Exception {
    if (args.length < 1) {
        throw new RuntimeException("Usage: " + myAppName + " port-file [arg(s)]");
    }
    // bind to a random port
    mySS = new ServerSocket(0);
    myPort = mySS.getLocalPort();
    // Write the port number to the given file
    File f = new File(args[0]);
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(Integer.toString(myPort).getBytes("UTF-8"));
    fos.close();
    System.out.println("INFO: " + myAppName + " created socket on port: " + myPort);
    System.out.flush();
}

94. UnicodeTest#generateManifest()

Project: jdk7u-jdk
Source File: UnicodeTest.java
View license
private static void generateManifest(String mainClass) throws Exception {
    String fileName = "UnicodeTest-src" + fileSeparator + "MANIFEST.MF";
    FileOutputStream out = new FileOutputStream(fileName);
    out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
    // Header lines are limited to 72 bytes.
    // The manifest spec doesn't say we have to break at character boundaries,
    // so we rudely break at byte boundaries.
    byte[] headerBytes = ("Main-Class: " + mainClass + "\n").getBytes("UTF-8");
    if (headerBytes.length <= 72) {
        out.write(headerBytes);
    } else {
        out.write(headerBytes, 0, 72);
        int start = 72;
        while (headerBytes.length > start) {
            out.write((byte) '\n');
            out.write((byte) ' ');
            int count = Math.min(71, headerBytes.length - start);
            out.write(headerBytes, start, count);
            start += count;
        }
    }
    out.close();
}

95. DirPollOperationTest#testBadFile()

Project: jPOS
Source File: DirPollOperationTest.java
View license
@Test
public void testBadFile() throws Exception {
    String filename = "dodgyTestFile.test";
    dirPoll.setProcessor(new DirPoll.FileProcessor() {

        @Override
        public void process(File name) throws DirPoll.DirPollException {
            fileProcessed = true;
            throw new DirPoll.DirPollException();
        }
    });
    dirPoll.setShouldArchive(true);
    dirPoll.setArchiveDateFormat(DATE_FORMAT_STRING);
    dirPoll.setShouldTimestampArchive(true);
    testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, filename));
    FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile);
    fileOutputStream.write("test".getBytes());
    fileOutputStream.flush();
    assertThat(testIncomingFile.exists(), is(true));
    File badDirectory = new File(absolutePathTo(RELATIVE_BAD_DIR));
    waitForFileProcessed();
    waitForNumFilesInDirOrTimeout(1, badDirectory, 200);
    assertThat(badDirectory.listFiles().length, is(1));
    assertThat(badDirectory.listFiles()[0].getName().length(), is(DATE_FORMAT_STRING.length() + filename.length() + 1));
}

96. DirPollOperationTest#testArchiveFile()

Project: jPOS
Source File: DirPollOperationTest.java
View license
@Test
public void testArchiveFile() throws IOException, InterruptedException {
    String filename = "dodgyTestFile.test";
    dirPoll.setShouldArchive(true);
    dirPoll.setArchiveDateFormat(DATE_FORMAT_STRING);
    dirPoll.setShouldTimestampArchive(true);
    testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, filename));
    FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile);
    fileOutputStream.write("test".getBytes());
    fileOutputStream.flush();
    assertThat(testIncomingFile.exists(), is(true));
    File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR));
    waitForFileProcessed();
    waitForNumFilesInDirOrTimeout(1, archiveDirectory, 200);
    assertThat(archiveDirectory.listFiles().length, is(1));
    assertThat(archiveDirectory.listFiles()[0].getName().length(), is(DATE_FORMAT_STRING.length() + filename.length() + 1));
}

97. DecryptedTempFileBody#writeMemoryToFile()

Project: k-9
Source File: DecryptedTempFileBody.java
View license
private void writeMemoryToFile() throws IOException {
    if (file != null) {
        throw new IllegalStateException("Body is already file-backed!");
    }
    if (data == null) {
        throw new IllegalStateException("Data must be fully written before it can be read!");
    }
    Log.d(K9.LOG_TAG, "Writing body to file for attachment access");
    file = File.createTempFile("decrypted", null, tempDirectory);
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(data);
    fos.close();
    data = null;
}

98. TestCopyCommandClusterChangedNameWithPartitioning#getExtraCreateArgs()

View license
@Override
public List<String> getExtraCreateArgs() throws Exception {
    PartitionStrategy partitionStrategy = new PartitionStrategy.Builder().hash("id", "part", 2).build();
    FileOutputStream psOut = new FileOutputStream(partitionStrategyJson);
    psOut.write(partitionStrategy.toString(true).getBytes());
    psOut.close();
    return ImmutableList.of("-p", partitionStrategyJson, "--set", "kite.writer.cache-size=20");
}

99. Weaver#writeClass()

Project: kilim
Source File: Weaver.java
View license
static void writeClass(ClassInfo ci) throws IOException {
    String className = ci.className.replace('.', File.separatorChar);
    String dir = outputDir + File.separatorChar + getDirName(className);
    mkdir(dir);
    // Convert name to fully qualified file name
    className = outputDir + File.separatorChar + className + ".class";
    if (ci.className.startsWith("kilim.S_")) {
        // Check if we already have that file
        if (new File(className).exists())
            return;
    }
    FileOutputStream fos = new FileOutputStream(className);
    fos.write(ci.bytes);
    fos.close();
    if (verbose) {
        System.out.println("Wrote: " + className);
    }
}

100. UnicodeTest#generateManifest()

Project: openjdk
Source File: UnicodeTest.java
View license
private static void generateManifest(String mainClass) throws Exception {
    File file = new File(UnicodeTestSrc, "MANIFEST.MF");
    FileOutputStream out = new FileOutputStream(file);
    out.write("Manifest-Version: 1.0\n".getBytes("UTF-8"));
    // Header lines are limited to 72 bytes.
    // The manifest spec doesn't say we have to break at character boundaries,
    // so we rudely break at byte boundaries.
    byte[] headerBytes = ("Main-Class: " + mainClass + "\n").getBytes("UTF-8");
    if (headerBytes.length <= 72) {
        out.write(headerBytes);
    } else {
        out.write(headerBytes, 0, 72);
        int start = 72;
        while (headerBytes.length > start) {
            out.write((byte) '\n');
            out.write((byte) ' ');
            int count = Math.min(71, headerBytes.length - start);
            out.write(headerBytes, start, count);
            start += count;
        }
    }
    out.close();
}