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. 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();
}

8. 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();
}

9. 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";
}

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. 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();
}

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. 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();
}

14. 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();
}

15. 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();
}

16. 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);
}

17. 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));
}

18. 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");
}

19. 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");
}

20. 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));
}

21. 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");
}

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. 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));
}

24. 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();
}

25. 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();
}

26. 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());
}

27. 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();
}

28. 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();
}

29. 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;
}

30. 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;
}

31. 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();
}

32. 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;
}

33. 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;
}

34. 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.";
}

35. 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();
}

36. 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();
}

37. 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();
}

38. 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...");
}

39. 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...");
}

40. 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");
}

41. 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();
}

42. 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...");
}

43. 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();
}

44. 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();
}

45. 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();
}

46. 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();
}

47. 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());
}

48. 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;
}

49. 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;
}

50. 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;
}

51. 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();
}

52. 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();
}

53. 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));
}

54. 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());
}

55. 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")));
    }
}

56. 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);
}

57. 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()));
}

58. 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());
    }
}

59. 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();
    [email protected]: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();
    [email protected]:on
    String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
    ourLog.info(resp);
    assertThat(((IntegerType) respParam.getParameter().get(0).getValue()).getValue(), greaterThan(1));
}

60. RemoteClassLoader#makeResource()

Project: hudson-2.x
Source File: RemoteClassLoader.java
View license
private File makeResource(String name, byte[] image) throws IOException {
    File tmpFile = createTempDir();
    File resource = new File(tmpFile, name);
    resource.getParentFile().mkdirs();
    FileOutputStream fos = new FileOutputStream(resource);
    fos.write(image);
    fos.close();
    deleteDirectoryOnExit(tmpFile);
    return resource;
}

61. TestSiddhiStateSnapshotAndRestore#testSimpleSiddhiQuery()

View license
@Test
public void testSimpleSiddhiQuery() throws Exception {
    String tmpdir = System.getProperty("java.io.tmpdir");
    System.out.println("temporary directory: " + tmpdir);
    String stateFile = tmpdir + "/siddhi-state";
    ExecutionPlanRuntime executionPlanRuntime = setupRuntimeForSimple();
    executionPlanRuntime.getInputHandler("testStream").send(new Object[] { "rename", "/tmp/pii" });
    byte[] state = executionPlanRuntime.snapshot();
    int length = state.length;
    FileOutputStream output = new FileOutputStream(stateFile);
    output.write(state);
    output.close();
    executionPlanRuntime.shutdown();
    ExecutionPlanRuntime restoredRuntime = setupRuntimeForSimple();
    FileInputStream input = new FileInputStream(stateFile);
    byte[] restoredState = new byte[length];
    input.read(restoredState);
    restoredRuntime.restore(restoredState);
    restoredRuntime.getInputHandler("testStream").send(new Object[] { "rename", "/tmp/pii" });
    input.close();
    restoredRuntime.shutdown();
}

62. StartupSettingsTest#writeSettingsFile()

View license
private void writeSettingsFile(File target) throws IOException {
    String settings = // It is odd that this is meant to be in an array, but oh well.
    "[{\n" + "  \"cluster\":\"" + CLUSTER + "\",\n" + "  \"id\":\"" + UUID.randomUUID() + "\",\n" + "  \"uri\":\"udp://127.0.0.1:50001\",\n" + "  \"gossip_interval\":1000,\n" + "  \"cleanup_interval\":10000,\n" + "  \"members\":[\n" + "    {\"cluster\": \"" + CLUSTER + "\",\"uri\":\"udp://127.0.0.1:5000\"}\n" + "  ]\n" + "}]";
    log.info("Using settings file with contents of:\n---\n" + settings + "\n---");
    FileOutputStream output = new FileOutputStream(target);
    output.write(settings.getBytes());
    output.close();
}

63. TestServerConfiguration#testCorruptionOfPolicyFile()

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);
    }
}

64. RandomAccessFileTest#test_read$B()

Project: j2objc
Source File: RandomAccessFileTest.java
View license
/**
     * java.io.RandomAccessFile#read(byte[])
     */
public void test_read$B() throws IOException {
    // Test for method int java.io.RandomAccessFile.read(byte [])
    FileOutputStream fos = new java.io.FileOutputStream(fileName);
    fos.write(fileString.getBytes(), 0, fileString.length());
    fos.close();
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
    byte[] rbuf = new byte[4000];
    raf.read(rbuf);
    assertEquals("Incorrect bytes returned from read", fileString, new String(rbuf, 0, fileString.length()));
    raf.close();
}

65. RandomAccessFileTest#test_read$BII()

Project: j2objc
Source File: RandomAccessFileTest.java
View license
/**
     * java.io.RandomAccessFile#read(byte[], int, int)
     */
public void test_read$BII() throws IOException {
    // Test for method int java.io.RandomAccessFile.read(byte [], int, int)
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
    byte[] rbuf = new byte[4000];
    FileOutputStream fos = new java.io.FileOutputStream(fileName);
    fos.write(fileString.getBytes(), 0, fileString.length());
    fos.close();
    raf.read(rbuf, 0, fileString.length());
    assertEquals("Incorrect bytes returned from read", fileString, new String(rbuf, 0, fileString.length()));
    raf.close();
}

66. RandomAccessFileTest#test_read_$BII_IndexOutOfBoundsException()

Project: j2objc
Source File: RandomAccessFileTest.java
View license
/**
     * java.io.RandomAccessFile#read(byte[], int, int)
     */
public void test_read_$BII_IndexOutOfBoundsException() throws IOException {
    FileOutputStream fos = new java.io.FileOutputStream(fileName);
    fos.write(fileString.getBytes(), 0, fileString.length());
    fos.close();
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
    byte[] rbuf = new byte[100];
    raf.close();
    try {
        raf.read(rbuf, -1, 0);
        fail("should throw IndexOutOfBoundsException");
    } catch (IndexOutOfBoundsException e) {
    }
}

67. OldRandomAccessFileTest#test_read$B()

Project: j2objc
Source File: OldRandomAccessFileTest.java
View license
/**
     * java.io.RandomAccessFile#read(byte[])
     */
public void test_read$B() throws IOException {
    FileOutputStream fos = new java.io.FileOutputStream(fileName);
    fos.write(testString.getBytes(), 0, testLength);
    fos.close();
    RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
    byte[] rbuf = new byte[testLength + 10];
    int bytesRead = raf.read(rbuf);
    assertEquals("Test 1: Incorrect number of bytes read. ", testLength, bytesRead);
    assertEquals("Test 2: Incorrect bytes read. ", testString, new String(rbuf, 0, testLength));
    bytesRead = raf.read(rbuf);
    assertTrue("Test 3: EOF (-1) expected. ", bytesRead == -1);
    raf.close();
    try {
        bytesRead = raf.read(rbuf);
        fail("Test 4: IOException expected.");
    } catch (IOException e) {
    }
}

68. Support_Resources#resourceToTempFile()

Project: j2objc
Source File: Support_Resources.java
View license
public static File resourceToTempFile(String path) throws IOException {
    File f = File.createTempFile("out", ".xml");
    f.deleteOnExit();
    FileOutputStream out = new FileOutputStream(f);
    InputStream xml = Support_Resources.class.getResourceAsStream(path);
    int b;
    while ((b = xml.read()) != -1) {
        out.write(b);
    }
    out.flush();
    out.close();
    xml.close();
    return f;
}

69. FileIOStreamT#main()

View license
public static void main(String[] args) throws IOException {
    // ???????
    FileInputStream fileInputStream = new FileInputStream(thisFilePath);
    // ???????
    FileOutputStream fileOutputStream = new FileOutputStream("data.txt");
    // ??????????
    byte[] inOutBytes = new byte[fileInputStream.available()];
    // ????????????inOutBytes??
    fileInputStream.read(inOutBytes);
    // ?inOutBytes??????data.txt???
    fileOutputStream.write(inOutBytes);
    fileOutputStream.close();
    fileInputStream.close();
}

70. ProcessAttachDebuggee#main()

View license
public static void main(String args[]) throws Exception {
    // bind to a random port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    // Write the port number to the given file
    File f = new File(args[0]);
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(Integer.toString(port).getBytes("UTF-8"));
    fos.close();
    System.out.println("Debuggee bound to port: " + port);
    System.out.flush();
    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();
    System.out.println("Debuggee shutdown.");
}

71. Test4067824#main()

Project: jdk7u-jdk
Source File: Test4067824.java
View license
public static void main(String[] args) throws Exception {
    ClassLoader cl = Test4067824.class.getClassLoader();
    try {
        Beans.instantiate(cl, "Test4067824");
    } catch (ClassNotFoundException exception) {
        if (exception.toString().indexOf("IllegalAccessException") < 0)
            throw new Error("unexpected exception", exception);
    }
    FileOutputStream fout = new FileOutputStream("foo.ser");
    fout.write(new byte[] { 1, 2, 3, 4, 5 });
    fout.close();
    try {
        // trying to instantiate corrupt foo.ser
        Beans.instantiate(cl, "foo");
        throw new Error("Instantiated corrupt .ser file OK!!??");
    } catch (ClassNotFoundException exception) {
    } catch (StreamCorruptedException exception) {
    }
}

72. FailingConstructors#realMain()

Project: jdk7u-jdk
Source File: FailingConstructors.java
View license
private static void realMain(String[] args) throws Throwable {
    test(false, new File(fileName));
    /* create the file and write its contents */
    File file = File.createTempFile(fileName, null);
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(FILE_CONTENTS.getBytes());
    fos.close();
    test(true, file);
    file.delete();
}

73. ConfigFileWithBlank#main()

Project: jdk7u-jdk
Source File: ConfigFileWithBlank.java
View license
public static void main(String[] args) throws Exception {
    File f = new File("a b c");
    FileOutputStream fos = new FileOutputStream(f);
    fos.write("".getBytes());
    fos.close();
    System.err.println(f.toURI());
    try {
        Configuration.getInstance("JavaLoginConfig", new URIParameter(f.toURI()));
    } finally {
        f.delete();
    }
}

74. 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);
}

75. 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();
}

76. 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();
}

77. 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));
}

78. 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));
}

79. 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"));
}

80. DirPollOperationTest#testDoNotArchiveFile()

Project: jPOS
Source File: DirPollOperationTest.java
View license
@Test
public void testDoNotArchiveFile() throws IOException, InterruptedException {
    dirPoll.setShouldArchive(false);
    testIncomingFile = new File(absolutePathTo(RELATIVE_REQUEST_DIR, "dodgyTestFile2.test"));
    FileOutputStream fileOutputStream = new FileOutputStream(testIncomingFile);
    fileOutputStream.write("test".getBytes());
    fileOutputStream.flush();
    assertThat(testIncomingFile.exists(), is(true));
    waitForFileProcessed();
    Thread.sleep(200);
    File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR));
    assertThat(archiveDirectory.listFiles().length, is(0));
}

81. DirPollOperationTest#testArchiveNoTimestamp()

Project: jPOS
Source File: DirPollOperationTest.java
View license
@Test
public void testArchiveNoTimestamp() throws Exception {
    String filename = "dodgyTestFile3.test";
    dirPoll.setShouldArchive(true);
    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));
    waitForFileProcessed();
    File archiveDirectory = new File(absolutePathTo(RELATIVE_ARCHIVE_DIR));
    waitForNumFilesInDirOrTimeout(1, archiveDirectory, 200);
    assertThat(archiveDirectory.listFiles().length, is(1));
    assertThat(archiveDirectory.listFiles()[0].getName().length(), is(filename.length()));
    assertThat(archiveDirectory.listFiles()[0].getName(), is(filename));
}

82. 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;
}

83. 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);
    }
}

84. 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");
}

85. 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());
}

86. 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();
}

87. 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();
}

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. 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();
}

90. 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();
}

91. 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();
}

92. 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;
}

93. 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();
}

94. 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;
}

95. Test4067824#main()

Project: openjdk
Source File: Test4067824.java
View license
public static void main(String[] args) throws Exception {
    ClassLoader cl = Test4067824.class.getClassLoader();
    try {
        Beans.instantiate(cl, "Test4067824");
    } catch (ClassNotFoundException exception) {
        if (exception.toString().indexOf("IllegalAccessException") < 0)
            throw new Error("unexpected exception", exception);
    }
    FileOutputStream fout = new FileOutputStream("foo.ser");
    fout.write(new byte[] { 1, 2, 3, 4, 5 });
    fout.close();
    try {
        // trying to instantiate corrupt foo.ser
        Beans.instantiate(cl, "foo");
        throw new Error("Instantiated corrupt .ser file OK!!??");
    } catch (ClassNotFoundException exception) {
    } catch (StreamCorruptedException exception) {
    }
}

96. RememberAppend#main()

Project: openjdk
Source File: RememberAppend.java
View license
public static void main(String[] args) throws Throwable {
    File f = File.createTempFile("tmp.file", null);
    f.deleteOnExit();
    try (FileOutputStream fos1 = new FileOutputStream(f.getPath(), true)) {
        fos1.write(bytes);
    }
    try (FileOutputStream fos1 = new FileOutputStream(f.getPath(), true);
        FileOutputStream fos2 = new FileOutputStream(fos1.getFD())) {
        fos2.write(bytes);
    }
    if (f.length() != 2 * bytes.length) {
        throw new RuntimeException("Append flag ignored");
    }
}

97. FailingConstructors#realMain()

Project: openjdk
Source File: FailingConstructors.java
View license
private static void realMain(String[] args) throws Throwable {
    test(false, new File(fileName));
    /* create the file and write its contents */
    File file = File.createTempFile(fileName, null);
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(FILE_CONTENTS.getBytes());
    fos.close();
    test(true, file);
    file.delete();
}

98. ConfigFileWithBlank#main()

Project: openjdk
Source File: ConfigFileWithBlank.java
View license
public static void main(String[] args) throws Exception {
    File f = new File("a b c");
    FileOutputStream fos = new FileOutputStream(f);
    fos.write("".getBytes());
    fos.close();
    System.err.println(f.toURI());
    try {
        Configuration.getInstance("JavaLoginConfig", new URIParameter(f.toURI()));
    } finally {
        f.delete();
    }
}

99. CrossRealm#xRealmAuth()

Project: openjdk
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");
    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);
}

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();
}