Java Examples for java.io.FileOutputStream

The following java examples will help you to understand the usage of java.io.FileOutputStream. These source code samples are taken from different open source projects.

Example 1
Project: Tank-master  File: WorkLoadFactoryTest.java View source code
/**
     * Run the String buildScriptXml(String,Workload) method test.
     * 
     * @throws Exception
     * 
     * @generatedBy CodePro at 9/10/14 10:40 AM
     */
@Test
public void testBuildScriptXml_1() throws Exception {
    WorkLoadFactory fixture = new WorkLoadFactory();
    String jobId = "";
    Workload workload = new Workload();
    String result = fixture.buildScriptXml(jobId, workload);
    // An unexpected exception was thrown in user code while executing this test:
    // java.lang.SecurityException: Cannot write to files while generating test cases
    // at
    // com.instantiations.assist.eclipse.junit.CodeProJUnitSecurityManager.checkWrite(CodeProJUnitSecurityManager.java:76)
    // at java.io.FileOutputStream.<init>(FileOutputStream.java:209)
    // at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
    // at org.apache.commons.configuration.AbstractFileConfiguration.save(AbstractFileConfiguration.java:490)
    // at
    // org.apache.commons.configuration.AbstractHierarchicalFileConfiguration.save(AbstractHierarchicalFileConfiguration.java:204)
    // at com.intuit.tank.settings.BaseCommonsXmlConfig.readConfig(BaseCommonsXmlConfig.java:63)
    // at com.intuit.tank.settings.TankConfig.<init>(TankConfig.java:78)
    // at
    // com.intuit.tank.api.service.v1.project.ProjectServiceUrlBuilder.getScriptXmlUrl(ProjectServiceUrlBuilder.java:29)
    // at com.intuit.tank.perfManager.workLoads.WorkLoadFactory.buildScriptXml(WorkLoadFactory.java:175)
    assertNotNull(result);
}
Example 2
Project: trie4j-master  File: CreateTail.java View source code
public static void main(String[] args) throws Exception {
    TailPatriciaTrie trie = new TailPatriciaTrie();
    for (String s : new WikipediaTitles("data/jawiki-20120220-all-titles-in-ns0.gz")) {
        trie.insert(s);
    }
    ConcatTailArrayBuilder ta = new ConcatTailArrayBuilder(trie.size());
    new TailLOUDSTrie(trie, ta);
    OutputStream os = new FileOutputStream("data/jawiki-20120220-tail");
    try {
    /*			CharSequence seq = ta.build().getTails();
			byte[] bytes = seq.toString().getBytes("UTF16");
			System.out.println(seq.length() + "chars.");
			System.out.println(bytes.length + "bytes.");
			os.write(bytes);
*/
    } finally {
        os.close();
    }
}
Example 3
Project: ARTPart-master  File: FileOutputStreamTest.java View source code
/**
     * java.io.FileOutputStream#FileOutputStream(java.lang.String,
     *boolean)
     */
public void test_ConstructorLjava_lang_StringZ() throws IOException {
    f = File.createTempFile("FileOutputStreamTest", "tst");
    fos = new FileOutputStream(f.getPath(), false);
    fos.write("HI".getBytes(), 0, 2);
    fos.close();
    fos = new FileOutputStream(f.getPath(), true);
    fos.write(fileString.getBytes());
    fos.close();
    byte[] buf = new byte[fileString.length() + 2];
    fis = new FileInputStream(f.getPath());
    fis.read(buf, 0, buf.length);
    assertTrue("Failed to create appending stream", new String(buf, 0, buf.length).equals("HI" + fileString));
}
Example 4
Project: android-sdk-sources-for-api-level-23-master  File: FileOutputStreamTest.java View source code
/**
     * java.io.FileOutputStream#FileOutputStream(java.lang.String,
     *boolean)
     */
public void test_ConstructorLjava_lang_StringZ() throws IOException {
    f = File.createTempFile("FileOutputStreamTest", "tst");
    fos = new FileOutputStream(f.getPath(), false);
    fos.write("HI".getBytes(), 0, 2);
    fos.close();
    fos = new FileOutputStream(f.getPath(), true);
    fos.write(fileString.getBytes());
    fos.close();
    byte[] buf = new byte[fileString.length() + 2];
    fis = new FileInputStream(f.getPath());
    fis.read(buf, 0, buf.length);
    assertTrue("Failed to create appending stream", new String(buf, 0, buf.length).equals("HI" + fileString));
}
Example 5
Project: android-15-master  File: CarouselViewUtilities.java View source code
/**
     * Debug utility to write the given bitmap to a file.
     *
     * @param context calling context
     * @param bitmap the bitmap to write
     * @param filename the name of the file to write
     * @return
     */
public static boolean writeBitmapToFile(Context context, Bitmap bitmap, String filename) {
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File file = new File(path, filename);
    boolean result = false;
    try {
        path.mkdirs();
        OutputStream os = new FileOutputStream(file);
        MediaScannerConnection.scanFile(context, new String[] { file.toString() }, null, null);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        result = true;
    } catch (IOException e) {
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
    return result;
}
Example 6
Project: vr-toolkit-master  File: DownloadFiles.java View source code
@Override
protected String doInBackground(String... sUrl) {
    try {
        URL url = new URL(sUrl[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();
        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(mPath);
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }
        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
    }
    return null;
}
Example 7
Project: eclipse-license-management-tools-master  File: GenSig.java View source code
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("Usage: GenSig nameOfFileToSign");
        System.exit(1);
    }
    PrivateKey priv = Utils.readPrivateKeyFromFile(args[1]);
    Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
    sig.initSign(priv);
    FileInputStream fis = new FileInputStream(args[0]);
    BufferedInputStream bufin = new BufferedInputStream(fis);
    byte[] buffer = new byte[1024];
    int len;
    while ((len = bufin.read(buffer)) >= 0) {
        sig.update(buffer, 0, len);
    }
    bufin.close();
    byte[] realSig = sig.sign();
    /* save the signature in a file */
    FileOutputStream sigfos = new FileOutputStream("sig");
    sigfos.write(realSig);
    sigfos.close();
}
Example 8
Project: hdt-java-master  File: LogArray64Dump.java View source code
/**
	 * @param args
	 * @throws Throwable 
	 */
public static void main(String[] args) throws Throwable {
    int num = 100;
    System.out.println("Bits: " + BitUtil.log2(num) + " Num: " + num);
    SequenceLog64 arr = new SequenceLog64(BitUtil.log2(num), num);
    for (int i = 0; i < num; i++) {
        arr.append(i);
    }
    FileOutputStream out = new FileOutputStream("logarr2.bin");
    arr.save(out, null);
    out.close();
    for (int i = 0; i < num; i++) {
        System.out.println(arr.get(i));
    }
    int bits = 7;
    for (int i = 0; i < 100; i++) {
        System.out.println(i + " values of " + bits + " bits: " + calculate(bits, i) + " bytes    Total bits: " + (bits * i) + " Bytes: " + (bits * i) / 8 + " Remaind: " + (bits * i) % 8);
    }
}
Example 9
Project: property-db-master  File: CarouselViewUtilities.java View source code
/**
     * Debug utility to write the given bitmap to a file.
     *
     * @param context calling context
     * @param bitmap the bitmap to write
     * @param filename the name of the file to write
     * @return
     */
public static boolean writeBitmapToFile(Context context, Bitmap bitmap, String filename) {
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File file = new File(path, filename);
    boolean result = false;
    try {
        path.mkdirs();
        OutputStream os = new FileOutputStream(file);
        MediaScannerConnection.scanFile(context, new String[] { file.toString() }, null, null);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        result = true;
    } catch (IOException e) {
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
    return result;
}
Example 10
Project: SecurePhoto-master  File: SPImageHandler.java View source code
@Override
public SPIWrapper saveFile(byte[] bytes) {
    File pictureFile;
    try {
        pictureFile = FileHandling.getOutputFile(SPImage.DEFAULT_EXTENSION);
    } catch (IOException e) {
        throw new RuntimeException("Cannot create output file");
    }
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(pictureFile);
        SPImage image = SPImage.getInstance(bytes, verifierProvider.getVerifiers());
        fileOutputStream.write(image.toByteArray());
        fileOutputStream.close();
        return new SPIWrapper(pictureFile, image.getHeader(), image.getFrameHash());
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("Cannot write to file %s", pictureFile.getAbsolutePath()));
    } catch (IOException e) {
        throw new RuntimeException("IOException: " + e.toString());
    }
}
Example 11
Project: ehour-master  File: ScreenshotTestRule.java View source code
public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            try {
                statement.evaluate();
            } catch (Throwable t) {
                captureScreenshot(frameworkMethod.getName());
                throw t;
            }
        }

        public void captureScreenshot(String fileName) {
            try {
                new File("target/surefire-reports/").mkdirs();
                FileOutputStream out = new FileOutputStream("target/surefire-reports/screenshot-" + fileName + ".png");
                out.write(driver.getScreenshotAs(OutputType.BYTES));
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
Example 12
Project: WordPress-Android-master  File: GravatarApiTest.java View source code
public void testGravatarUploadRequest() throws IOException {
    final String fileContent = "abcdefg";
    File tempFile = new File(getInstrumentation().getTargetContext().getCacheDir(), "tempFile.jpg");
    FileOutputStream fos = new FileOutputStream(tempFile);
    fos.write(fileContent.getBytes());
    fos.flush();
    fos.close();
    final String email = "[email protected]";
    Request uploadRequest = GravatarApi.prepareGravatarUpload(email, tempFile);
    assertEquals("POST", uploadRequest.method());
    RequestBody requestBody = uploadRequest.body();
    assertTrue(requestBody.contentType().toString().startsWith("multipart/form-data"));
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    final String body = buffer.readUtf8();
    assertTrue(body.contains("Content-Disposition: form-data; name=\"account\""));
    assertTrue(body.contains("Content-Length: " + email.length()));
    assertTrue(body.contains(email));
    assertTrue(body.contains("Content-Disposition: form-data; name=\"filedata\"; filename=\"" + tempFile.getName() + "\""));
    assertTrue(body.contains("Content-Type: multipart/form-data"));
    assertTrue(body.contains(fileContent));
}
Example 13
Project: REST-OCD-Services-master  File: ExcelFileGenerator.java View source code
public void genFile(Map<String, Object[]> data) {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Data");
    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        rownum = Integer.parseInt(key);
        Row row = sheet.createRow(rownum);
        Object[] objectArray = data.get(key);
        int cellnum = 0;
        for (Object o : objectArray) {
            Cell c = row.createCell(cellnum++);
            if (o instanceof String) {
                c.setCellValue((String) o);
            }
            if (o instanceof Double) {
                c.setCellValue((Double) o);
            }
            if (o instanceof Integer) {
                c.setCellValue((Integer) o);
            }
        }
    }
    try {
        FileOutputStream out = new FileOutputStream(new File("Evaluation.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("Excel file written");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 14
Project: fdroidclient-master  File: AssetUtils.java View source code
@Nullable
public static File copyAssetToDir(Context context, String assetName, File directory) {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile(assetName, ".testasset", directory);
        Log.i(TAG, "Copying asset file " + assetName + " to directory " + directory);
        input = context.getAssets().open(assetName);
        output = new FileOutputStream(tempFile);
        Utils.copy(input, output);
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        Utils.closeQuietly(output);
        Utils.closeQuietly(input);
    }
    return tempFile;
}
Example 15
Project: rayo-server-master  File: PropertiesBasedProvisioningServiceTest.java View source code
@Before
public void setup() throws Exception {
    propsFile = File.createTempFile("temp", ".properties");
    propsFile.deleteOnExit();
    tempProvisioningFile = File.createTempFile("temp", ".properties");
    tempProvisioningFile.deleteOnExit();
    InputStream sourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("test-provisioning.properties");
    Properties sourceProperties = new Properties();
    sourceProperties.load(sourceStream);
    sourceProperties.put(PropertiesBasedStorageServiceClient.ROUTING_PROPERTIES_FILE, propsFile.getAbsolutePath());
    sourceProperties.put(PropertiesBasedStorageServiceClient.PROPERTIES_RELOAD_INTERVAL, "500");
    sourceStream.close();
    FileOutputStream fos = new FileOutputStream(tempProvisioningFile);
    sourceProperties.store(fos, null);
    fos.close();
    propertiesFile = tempProvisioningFile.getAbsolutePath();
    provisioningService = new PropertiesBasedProvisioningAgent();
    super.setup();
}
Example 16
Project: my-ministry-assistant-master  File: FileUtils.java View source code
public static void copyFile(File fromFile, File toFile) throws IOException {
    FileInputStream fromFileStream = new FileInputStream(fromFile);
    FileOutputStream toFileStream = new FileOutputStream(toFile);
    FileChannel fromChannel = fromFileStream.getChannel();
    FileChannel toChannel = toFileStream.getChannel();
    try {
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        if (fromChannel != null)
            fromChannel.close();
        if (toChannel != null)
            toChannel.close();
        fromFileStream.close();
        toFileStream.close();
    }
}
Example 17
Project: JDK-master  File: ORBProperties.java View source code
public static void main(String[] args) {
    try {
        // Check if orb.properties exists
        String javaHome = System.getProperty("java.home");
        File propFile = new File(javaHome + File.separator + "lib" + File.separator + "orb.properties");
        if (propFile.exists())
            return;
        // Write properties to orb.properties
        FileOutputStream out = new FileOutputStream(propFile);
        PrintWriter pw = new PrintWriter(out);
        try {
            pw.println(ORB_CLASS);
            pw.println(ORB_SINGLETON_CLASS);
        } finally {
            pw.close();
            out.close();
        }
    } catch (Exception ex) {
    }
}
Example 18
Project: AndroidPlugin-master  File: MyApplication.java View source code
@Override
protected void loadPluginClients() {
    AssetManager asset = getAssets();
    try {
        for (String s : asset.list("apks")) {
            File dex = getDir("dex", Context.MODE_PRIVATE);
            dex.mkdir();
            File plugin = new File(dex, s);
            InputStream fis = getAssets().open("apks/" + s);
            FileOutputStream fos = new FileOutputStream(plugin);
            byte[] buffer = new byte[0xFF];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
            PluginClientManager.sharedInstance(this).addPluginClient(plugin.getAbsolutePath());
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}
Example 19
Project: open-mika-master  File: jdk11.java View source code
public void test(TestHarness testharness) {
    TestHarness harness = null;
    try {
        FileOutputStream fos = new FileOutputStream("tmpfile");
        try {
            FileDescriptor fd = fos.getFD();
            harness.check(fd.valid(), "valid()");
            try {
                fd.sync();
                harness.check(true, "sync()");
            } catch (SyncFailedException e) {
                harness.debug(e);
                harness.fail("SyncFailedException thrown");
            }
        } catch (IOException e) {
            harness.fail("Can't get FileDescriptor");
        }
    } catch (FileNotFoundException e) {
        harness.fail("Can't make file 'tmpfile'");
    }
}
Example 20
Project: sysart-itext-master  File: HelloHtml.java View source code
/**
	 * Generates an HTML page with the text 'Hello World'
	 * 
	 * @param args no arguments needed here
	 */
public static void main(String[] args) {
    System.out.println("Hello World");
    // step 1: creation of a document-object
    Document document = new Document();
    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a HTML-stream to a file
        HtmlWriter.getInstance(document, new FileOutputStream("HelloWorld.html"));
        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document
        document.add(new Paragraph("Hello World"));
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5: we close the document
    document.close();
}
Example 21
Project: SRE-RoboCode-master  File: Loader.java View source code
private static void downloadFile(String libraries, String directory, String file) throws IOException {
    URL url = new URL(libraries + file);
    final URLConnection con = url.openConnection();
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        is = con.getInputStream();
        fos = new FileOutputStream(directory + file);
        do {
            final int b = is.read();
            if (b == -1) {
                break;
            } else {
                fos.write(b);
            }
        } while (true);
    } finally {
        if (fos != null) {
            fos.close();
        }
        if (is != null) {
            is.close();
        }
    }
}
Example 22
Project: molgenis-master  File: CsvIteratorTest.java View source code
@Test
public void testIterator() throws IOException {
    InputStream in = getClass().getResourceAsStream("/testdata.csv");
    File csvFile = new File(FileUtils.getTempDirectory(), "testdata.csv");
    FileCopyUtils.copy(in, new FileOutputStream(csvFile));
    CsvIterator it = new CsvIterator(csvFile, "testdata", null, null, entityType);
    assertEquals(it.getColNamesMap().keySet(), Sets.newLinkedHashSet(Arrays.asList("col1", "col2")));
    assertEquals(Iterators.size(it), 5);
    it = new CsvIterator(csvFile, "testdata", null, null, entityType);
    Entity entity = it.next();
    assertEquals(entity.get("col1"), "val1");
    assertEquals(entity.get("col2"), "val2");
}
Example 23
Project: hank-master  File: CurlyMerger.java View source code
@Override
public long[] merge(final CurlyFilePath base, final List<String> deltaRemoteFiles, final PartitionRemoteFileOps partitionRemoteFileOps) throws IOException {
    long[] offsetAdjustments = new long[deltaRemoteFiles.size() + 1];
    offsetAdjustments[0] = 0;
    // Open the base in append mode
    File baseFile = new File(base.getPath());
    FileOutputStream baseOutputStream = new FileOutputStream(baseFile, true);
    try {
        // Loop over deltas and append them to the base in order, keeping track of offset adjustments
        long totalOffset = baseFile.length();
        int i = 1;
        for (String deltaRemoteFile : deltaRemoteFiles) {
            offsetAdjustments[i] = totalOffset;
            InputStream deltaRemoteInputStream = partitionRemoteFileOps.getInputStream(deltaRemoteFile);
            try {
                LOG.info("Merging remote file " + deltaRemoteFile + " into file " + base.getPath());
                long bytesCopied = IOStreamUtils.copy(deltaRemoteInputStream, baseOutputStream);
                totalOffset += bytesCopied;
            } finally {
                deltaRemoteInputStream.close();
            }
            i++;
        }
    } finally {
        // Close base streams
        baseOutputStream.close();
    }
    return offsetAdjustments;
}
Example 24
Project: oobd-master  File: CreateLargeCompressedMail.java View source code
public static void main(String args[]) throws Exception {
    //
    // create the generator for creating an smime/compressed message
    //
    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();
    //
    // create the base for our message
    //
    MimeBodyPart msg = new MimeBodyPart();
    msg.setDataHandler(new DataHandler(new FileDataSource(new File(args[0]))));
    msg.setHeader("Content-Type", "application/octet-stream");
    msg.setHeader("Content-Transfer-Encoding", "binary");
    MimeBodyPart mp = gen.generate(msg, SMIMECompressedGenerator.ZLIB);
    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);
    Address fromUser = new InternetAddress("\"Eric H. Echidna\"<[email protected]>");
    Address toUser = new InternetAddress("[email protected]");
    MimeMessage body = new MimeMessage(session);
    body.setFrom(fromUser);
    body.setRecipient(Message.RecipientType.TO, toUser);
    body.setSubject("example compressed message");
    body.setContent(mp.getContent(), mp.getContentType());
    body.saveChanges();
    body.writeTo(new FileOutputStream("compressed.message"));
}
Example 25
Project: AudioPlayer-master  File: CrashHandler.java View source code
private boolean handleExption(Thread thread, Throwable ex) {
    File logfile = new File(APP.Config.LOGPATH + "log.txt");
    try {
        if (!logfile.exists())
            logfile.createNewFile();
        FileOutputStream fileoutstream = new FileOutputStream(logfile, true);
        OutputStreamWriter osw = new OutputStreamWriter(fileoutstream);
        PrintWriter pw = new PrintWriter(osw);
        pw.println(ex.getLocalizedMessage());
        StackTraceElement[] ste = ex.getStackTrace();
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd    hh:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        pw.println(date);
        pw.println();
        for (int i = 0; i < ste.length; i++) {
            pw.println(ste[i].toString());
        }
        pw.println();
        pw.println();
        pw.close();
        osw.close();
        fileoutstream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return true;
}