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-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 5
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 6
Project: eclipse-license-management-tools-master  File: SignLicense.java View source code
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("Usage: SignLicense licenseFile privateKey");
        System.exit(1);
    }
    Properties license = new Properties();
    license.load(new FileInputStream(args[0]));
    PrivateKey privateKey = Utils.readPrivateKeyFromFile(args[1]);
    Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
    signature.initSign(privateKey);
    String[] propKeys = license.keySet().toArray(new String[0]);
    Arrays.sort(propKeys);
    for (String propKey : propKeys) {
        if (!"Signature".equals(propKey)) {
            String propValue = license.getProperty(propKey);
            signature.update(propValue.getBytes("UTF-8"));
        }
    }
    byte[] sig = signature.sign();
    license.setProperty("Signature", new String(Base64.encodeBase64(sig)));
    license.store(new FileOutputStream(args[0]), null);
}
Example 7
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 8
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 9
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 10
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 11
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 12
Project: fdroidclient-master  File: TestUtils.java View source code
public static File copyResourceToTempFile(String resourceName) {
    File tempFile = null;
    InputStream input = null;
    OutputStream output = null;
    try {
        tempFile = File.createTempFile(resourceName + "-", ".testasset");
        input = TestUtils.class.getClassLoader().getResourceAsStream(resourceName);
        output = new FileOutputStream(tempFile);
        Utils.copy(input, output);
    } catch (IOException e) {
        e.printStackTrace();
        if (tempFile != null && tempFile.exists()) {
            assertTrue(tempFile.delete());
        }
        fail();
        return null;
    } finally {
        Utils.closeQuietly(output);
        Utils.closeQuietly(input);
    }
    return tempFile;
}
Example 13
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 14
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 15
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 16
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 17
Project: open-mika-master  File: jdk12.java View source code
public void test(TestHarness harness) {
    // pick a directory we know doesn't exist
    String tmpfile = "./asdfghj/mauve-fileout.tst";
    try {
        new FileOutputStream(tmpfile);
        harness.fail("No exception thrown");
    } catch (FileNotFoundException t) {
        harness.check(true, "new(string) Threw correct exception");
    }
    try {
        new FileOutputStream(tmpfile, true);
        harness.fail("No exception thrown");
    } catch (FileNotFoundException t) {
        harness.check(true, "new(string, boolean) Threw correct exception");
    }
}
Example 18
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 19
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 20
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 21
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 22
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 23
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;
}
Example 24
Project: btpka3.github.com-master  File: Zip.java View source code
public static void main(String[] args) throws IOException {
    String zipFile = "/tmp/big.zip";
    new File(zipFile).delete();
    FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
    CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());
    ZipOutputStream zos = new ZipOutputStream(cos);
    ZipEntry entry = new ZipEntry("test.txt");
    zos.putNextEntry(entry);
    WritableByteChannel channel = Channels.newChannel(zos);
    ByteBuffer buf = ByteBuffer.allocate(1024 * 1024);
    int COUNT = 12;
    // COUNT =  300* 1024 * 1024;
    int c = 0;
    while (c < COUNT) {
        int fillCount = COUNT - c >= buf.capacity() ? buf.capacity() : COUNT - c;
        fillBuf(buf, fillCount);
        buf.flip();
        channel.write(buf);
        buf.compact();
        c += fillCount;
    }
    channel.close();
    System.out.printf("Done. see : " + zipFile);
}
Example 25
Project: org.eclipse.ecr-master  File: SerializableInputStreamTest.java View source code
public void testFileBlobSerialization() throws Exception {
    URL url = getResource("org.eclipse.ecr.core.api.test", "resources/test.blob");
    assertNotNull(url);
    InputStream sin = new SerializableInputStream(url.openStream());
    File tmp = File.createTempFile("SerializableISTest-", ".tmp");
    tmp.deleteOnExit();
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmp));
    out.writeObject(sin);
    out.close();
    ObjectInputStream oin = new ObjectInputStream(new FileInputStream(tmp));
    sin = (InputStream) oin.readObject();
    byte[] bytes1 = FileUtils.readBytes(url.openStream());
    byte[] bytes2 = FileUtils.readBytes(sin);
    assertTrue(Arrays.equals(bytes1, bytes2));
}
Example 26
Project: Musubi-Android-master  File: HTTPDownloadFileToExternalTask.java View source code
@Override
public String doInBackground(String... urls) {
    for (String url : urls) {
        FileOutputStream out = null;
        InputStream in = null;
        try {
            URL apkUrl = new URL(url);
            HttpURLConnection c = (HttpURLConnection) apkUrl.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            String PATH = Environment.getExternalStorageDirectory() + "/download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "app.apk");
            out = new FileOutputStream(outputFile);
            in = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) != -1) {
                out.write(buffer, 0, len1);
            }
            return outputFile.getPath();
        } catch (IOException e) {
        } finally {
            try {
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
            } catch (IOException e) {
                Log.e("HTTPDownloadtoexternal", "failed to close streams for http external", e);
            }
        }
    }
    return null;
}
Example 27
Project: deb-kitkat-storage-access-framework-master  File: ParcelFileDescriptorTest.java View source code
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void testThatPipeShouldWorkProperly() throws Exception {
    final String givenData = "Hello, ParcelFileDescriptor.";
    final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
    final ParcelFileDescriptor source = pipe[0];
    final ParcelFileDescriptor sink = pipe[1];
    final InputStream in = new FileInputStream(source.getFileDescriptor());
    final OutputStream out = new ByteArrayOutputStream();
    new AsyncTask<ParcelFileDescriptor, Void, Void>() {

        @Override
        protected Void doInBackground(ParcelFileDescriptor... params) {
            //Simulates long periodic network operation
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException ignore) {
            }
            ParcelFileDescriptor pfd = params[0];
            FileDescriptor fd = pfd.getFileDescriptor();
            FileOutputStream out = new FileOutputStream(fd);
            byte[] data = givenData.getBytes();
            try {
                out.write(data, 0, data.length);
                out.close();
                pfd.close();
            } catch (IOException ignore) {
            }
            return null;
        }
    }.execute(sink);
    final byte[] buffer = new byte[8192];
    for (int count; (count = in.read(buffer)) > -1; ) {
        out.write(buffer, 0, count);
    }
    assertThat(out.toString()).isEqualTo(givenData);
}
Example 28
Project: securereader-master  File: APKInstaller.java View source code
public void installAPK(int apk) {
    try {
        String tempFileName = "apktoinstall.apk";
        InputStream in = applicationContext.getResources().openRawResource(apk);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int size = 0;
        byte[] buffer = new byte[1024];
        while ((size = in.read(buffer, 0, 1024)) >= 0) {
            baos.write(buffer, 0, size);
        }
        in.close();
        FileOutputStream fout = applicationContext.openFileOutput(tempFileName, Context.MODE_WORLD_READABLE);
        fout.write(baos.toByteArray());
        fout.close();
        File tempFile = applicationContext.getFileStreamPath(tempFileName);
        tempFile.setReadable(true);
        installAPK(tempFile);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Example 29
Project: rsimulator-master  File: FileUtilsTest.java View source code
@Test
public void testRead() {
    String resource = "/test1/Test.properties";
    try {
        File file = new File(getClass().getResource(resource).getPath());
        String content = fileUtils.read(file.toPath());
        String cachedContent = fileUtils.read(file.toPath());
        assertNotNull("classFileContent", content);
        assertNotNull("cachedClassFileContent", cachedContent);
        assertSame(content, cachedContent);
        // Rewrite the file to test that FileUtilsCacheinterceptor reads a file that has been modified.
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(content.getBytes());
        fos.close();
        cachedContent = fileUtils.read(file.toPath());
        assertNotSame(content, cachedContent);
    } catch (IOException e) {
        fail(e.getMessage());
    }
}
Example 30
Project: AndroidLibraryProject-master  File: BackupDb.java View source code
/*
	 * Method to copy the database file to SD card
	 * */
public void backupDb() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        if (sd.canWrite()) {
            String backupDBPath;
            String currentDBPath;
            currentDBPath = "/data/" + pkgName + "/databases/contextAwareFramework.db";
            if (fileName != null) {
                backupDBPath = fileName;
            } else {
                backupDBPath = "contextdbbkp.db";
            }
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);
            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 31
Project: extension-aws-master  File: UploadDiskFileItem.java View source code
public OutputStream getOutputStream() throws IOException {
    // item.putProperty("offset", inReq.getRequestParameter("offset"));
    // log.info("Uploading from offset: " + item.get("offset"));
    OutputStream fos;
    File file = getTempFile();
    if (fieldSeek > 0 && file.length() == fieldSeek) {
        fos = new FileOutputStream(file, true);
    } else {
        fos = new FileOutputStream(getTempFile());
    }
    return new BufferedOutputStream(fos) {

        public void write(byte[] bytes, int one, int two) throws IOException {
            //Put breakpoint here to slow down progress SLOWDOWN
            //						try
            //						{
            //							Thread.sleep(100);
            //						}
            //						catch( Exception ex)
            //						{
            //							
            //						}
            super.write(bytes, one, two);
        }
    };
}
Example 32
Project: abmash-master  File: IOTools.java View source code
public static File convertStreamToFile(InputStream inputStream, String extension) {
    try {
        File tmpFile = File.createTempFile("file", "." + extension);
        tmpFile.deleteOnExit();
        // write the inputStream to a FileOutputStream
        OutputStream out = new FileOutputStream(tmpFile);
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        inputStream.close();
        out.flush();
        out.close();
        return tmpFile;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 33
Project: osmdroid-master  File: MapsForgeMapTileProviderDirectTest.java View source code
public void test_getMapTile_found() throws RemoteException, FileNotFoundException, BitmapTileSourceBase.LowMemoryException, IOException {
    for (int i = 3; i < 22; i++) {
        final MapTile tile = new MapTile(i, 3, 4);
        BitmapDrawable drawable = (BitmapDrawable) source.renderTile(tile);
        assertNotNull(tile.toString() + " failed", drawable);
    //new File(OpenStreetMapTileProviderConstants.TILE_PATH_BASE.getPath() + "/" + tile.toString()).mkdirs();
    //FileOutputStream fos = new FileOutputStream(OpenStreetMapTileProviderConstants.TILE_PATH_BASE.getPath() + "/" + tile.toString() + ".png");
    //((BitmapDrawable) drawable).getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fos);
    //fos.close();
    }
}
Example 34
Project: picard-tools-master  File: FileFaker.java View source code
public void fakeFile(final File cycleFile, Integer size) throws IOException {
    if (size == null) {
        size = 1;
    }
    this.size = size;
    final OutputStream outputStream;
    if (BclReader.isGzipped(cycleFile))
        outputStream = new GZIPOutputStream(new FileOutputStream(cycleFile));
    else if (BclReader.isBlockGzipped(cycleFile))
        outputStream = new BlockCompressedOutputStream(cycleFile);
    else
        outputStream = new FileOutputStream(cycleFile);
    final WritableByteChannel channel = Channels.newChannel(outputStream);
    final ByteBuffer buffer = ByteBuffer.allocate(this.bufferSize());
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    fakeFile(buffer);
    buffer.flip();
    channel.write(buffer);
    channel.close();
    outputStream.close();
}
Example 35
Project: idnadrev-master  File: UmlDiagramRender.java View source code
public File generatePng(String uml, double width, Path path) {
    StringBuilder builder = new StringBuilder();
    builder.append("@startuml\n");
    builder.append("scale ");
    builder.append((int) width);
    builder.append(" width \n");
    builder.append("skinparam shadowing false\n");
    builder.append(uml);
    builder.append("\[email protected]");
    try {
        try (FileOutputStream outStream = new FileOutputStream(path.toFile())) {
            SourceStringReader reader = new SourceStringReader(builder.toString());
            FileFormatOption fileFormatOption = new FileFormatOption(FileFormat.PNG);
            String desc = reader.generateImage(outStream, fileFormatOption);
            log.info(desc);
        }
        return path.toFile();
    } catch (Exception e) {
        log.error("Could not create uml diagram", e);
        return null;
    }
}
Example 36
Project: jaamsim-master  File: BinaryExporter.java View source code
public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("Usage: BinaryExporter [collada-input-filename] [jsb-binary-output-filename]");
        return;
    }
    String inputName = args[0];
    String outputName = args[1];
    try {
        ColParser.setKeepData(true);
        MeshData data = ColParser.parse(new URI("file:///" + inputName));
        DataBlock block = data.getDataAsBlock();
        File outFile = new File(outputName);
        FileOutputStream outStream = new FileOutputStream(outFile);
        BlockWriter.writeBlock(outStream, block);
    } catch (Exception ex) {
        LogBox.renderLogException(ex);
    }
}
Example 37
Project: MobileSensing-master  File: UploadServlet.java View source code
/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    archive_dir = getServletConfig().getInitParameter("localpath");
    Long time = System.currentTimeMillis();
    String format = "unknown";
    MimeType type;
    try {
        type = new MimeType(request.getContentType());
        format = type.getSubType();
    } catch (MimeTypeParseException e1) {
        e1.printStackTrace();
    }
    try {
        String uuid = request.getHeader("uuid");
        String filePath = new StringBuffer(archive_dir).append(uuid).toString();
        String fileName = new StringBuffer(archive_dir).append(uuid).append("-").append(time).append(".").append(format).toString();
        File dir = new File(filePath);
        if ((dir.exists() && dir.isDirectory()) || dir.mkdir()) {
            FileOutputStream out = new FileOutputStream(new File(fileName));
            ServletInputStream in = request.getInputStream();
            try {
                byte buffer[] = new byte[1024];
                int cnt = in.read(buffer);
                while (cnt != -1) {
                    out.write(buffer, 0, cnt);
                    cnt = in.read(buffer);
                }
                response.setStatus(HttpServletResponse.SC_OK);
            } finally {
                out.close();
                in.close();
            }
        }
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Example 38
Project: jentrata-msh-master  File: MessageRepository.java View source code
public void persistMessage(AS2Message message) {
    if (!isDisabled && message != null) {
        try {
            String type = message.isDispositionNotification() ? DEFAULT_AS2_RECEIPT_TYPE : DEFAULT_AS2_MESSAGE_TYPE;
            PayloadCache cache = createPayloadCache(message.getMessageID(), message.getFromPartyID(), message.getToPartyID(), type);
            FileOutputStream fos = new FileOutputStream(cache.getCache());
            message.writeTo(fos);
            fos.close();
            cache.checkIn();
        } catch (Exception e) {
            getModule().getLogger().warn("Unable to persist message to local repository", e);
        }
    }
}
Example 39
Project: j2objc-master  File: PosixTest.java View source code
// Verify Issue 554 fix, where Posix.preadBytes used incorrect system call.
public void testPreadBytes() throws Exception {
    final String testString = "hello, world!";
    byte[] bytesToWrite = testString.getBytes("UTF-8");
    ByteBuffer buf = ByteBuffer.allocate(bytesToWrite.length);
    File tmpFile = File.createTempFile("preadbug-", ".tmp");
    tmpFile.deleteOnExit();
    try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
        fos.write(bytesToWrite);
    }
    try (RandomAccessFile raf = new RandomAccessFile(tmpFile, "r");
        FileChannel channel = raf.getChannel()) {
        channel.read(buf, 0);
    }
    String dstString = new String(buf.array(), "UTF-8");
    assertEquals(testString, dstString);
}
Example 40
Project: MD-BiliBili-master  File: DownloadXML.java View source code
@Override
public void call(Subscriber<? super File> subscriber) {
    String errorMessage = "";
    URL url = null;
    String filename = null;
    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    FileOutputStream fileStream = null;
    URLConnection connection = null;
    File file = null;
    final int DOWNLOAD_BUFFER_SIZE = 1024;
    try {
        url = new URL(uriString);
        connection = url.openConnection();
        connection.setUseCaches(false);
        if (StorageUtil.isExternalStorageAvailable()) {
            filename = uriString.substring(uriString.lastIndexOf('=') + 1) + ".xml";
            file = new File(BilibiliApplication.getApplication().getExternalFilesDir("danmaku"), filename);
            if (file.exists()) {
                file.delete();
            }
            inputStream = new BufferedInputStream(connection.getInputStream());
            fileStream = new FileOutputStream(file);
            outputStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
            byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(data, 0, data.length)) >= 0) {
                outputStream.write(data, 0, bytesRead);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        errorMessage = e.getMessage();
    } finally {
        try {
            if (outputStream != null)
                outputStream.close();
            if (inputStream != null)
                inputStream.close();
            if (fileStream != null)
                fileStream.close();
        } catch (IOException ignored) {
        }
    }
    if (TextUtils.isEmpty(errorMessage)) {
        subscriber.onNext(file);
    } else {
        subscriber.onError(new Exception(errorMessage));
    }
}
Example 41
Project: ProjectModel-master  File: ObjectXmlencoder.java View source code
/**  
     * 把java的可序列化的对象(实现Serializable接口)序列化保存到XML文件里面,如果想一次保存多个可序列化对象请用集合进行封装  
     * 保存时将会用现在的对象原来的XML文件内容  
     *   
     * @param obj  
     *            要序列化的可序列化的对象  
     * @param fileName  
     *            带完全的保存路径的文件名  
     * @throws FileNotFoundException  
     *             指定位置的文件不存在  
     * @throws IOException  
     *             输出时发生异常  
     * @throws Exception  
     *             其他运行时异常  
     */
public static void objectXmlEncoder(Object obj, String fileName) {
    // 创建输出文件   
    File fo = new File(fileName);
    // 文件不存在,就创建该文件   
    if (!fo.exists()) {
        // 先创建文件的目录   
        String path = fileName.substring(0, fileName.lastIndexOf('.'));
        File pFile = new File(path);
        pFile.mkdirs();
    }
    // 创建文件输出流   
    FileOutputStream fos = null;
    XMLEncoder encoder = null;
    try {
        fos = new FileOutputStream(fo);
        // 创建XML文件对象输出类实例   
        encoder = new XMLEncoder(fos);
        // 对象序列化输出到XML文件   
        encoder.writeObject(obj);
        encoder.flush();
        // 关闭序列化工具   
        encoder.close();
        // 关闭输出流   
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (encoder != null) {
            encoder.close();
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 42
Project: framework-master  File: DownloadLargeFileResource.java View source code
private void createFile() {
    try {
        File hugeFile = File.createTempFile("huge", ".txt");
        hugeFile.deleteOnExit();
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(hugeFile));
        int writeAtOnce = 1024 * 1024;
        byte[] b = new byte[writeAtOnce];
        for (int i = 0; i < fileSize; i += writeAtOnce) {
            os.write(b);
        }
        os.close();
        hugeFileResource = new FileResource(hugeFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 43
Project: watchlist-master  File: FileUtil.java View source code
// Copy file from source to destination
public static void copyFile(File source, File destination) throws IOException {
    FileInputStream fromFile = new FileInputStream(source);
    FileOutputStream toFile = new FileOutputStream(destination);
    FileChannel fromChannel = null;
    FileChannel toChannel = null;
    try {
        fromChannel = fromFile.getChannel();
        toChannel = toFile.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        try {
            if (fromChannel != null) {
                fromChannel.close();
            }
        } finally {
            if (toChannel != null) {
                toChannel.close();
            }
        }
    }
}
Example 44
Project: solmix-master  File: DownLoadFileTest.java View source code
//    @Test
public void test() {
    try {
        InputStream is = new URL(null, "mvn:org.apache.karaf.shell/org.apache.karaf.shell.wrapper/2.3.3", new org.ops4j.pax.url.mvn.Handler()).openStream();
        File f = new File("/home/solmix/abc.jar");
        if (!f.exists())
            f.createNewFile();
        FileOutputStream fs = new FileOutputStream(f);
        IOUtils.copyStreams(is, fs);
        IOUtils.closeQuitely(is);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 45
Project: gpu-garbage-collection-master  File: R1722506.java View source code
public static void main(String[] args) {
    String filename = System.getProperty("java.io.tmpdir") + "/filetest.tmp";
    try {
        File newIndexFile = new File(filename);
        DataOutputStream stream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newIndexFile, false), 2048));
        for (int i = 0; i < 50; i++) stream.writeInt(i);
        stream.close();
        long streamLen = (new File(filename)).length();
        RandomAccessFile raFile = new RandomAccessFile(filename, "rw");
        System.out.println(streamLen == (new File(filename)).length());
        raFile.close();
    } catch (Exception e) {
        System.err.println("Caught exception: " + e);
    } finally {
        (new File(filename)).delete();
    }
}
Example 46
Project: HR-WebServices-Examples-Java-master  File: MTOMSampleSkeleton.java View source code
/**
	 * 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;
}
Example 47
Project: xmind-master  File: ShowWelcomeService.java View source code
public void run() {
    IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
    if (window != null) {
        new WelcomeDialog(window.getShell()).open();
        //set value to properties file.
        properties.setProperty(NO_FIRST_START, Boolean.toString(true));
        try {
            properties.store(new FileOutputStream(propertiesFile), null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Example 48
Project: topodroid-master  File: PTString.java View source code
void write(FileOutputStream fs) {
    try {
        int len = _str.length();
        do {
            byte b = (byte) (len & 0x7f);
            len = len >> 7;
            if (len > 0) {
                b |= 0x80;
            }
            fs.write(b);
        } while (len > 0);
        if (_str.length() > 0) {
            byte[] chars = _str.getBytes();
            fs.write(chars, 0, _str.length());
        }
    } catch (IOException e) {
    }
}
Example 49
Project: dk-master  File: HttpsUtils.java View source code
public void httpss(String url, String from) throws NoSuchAlgorithmException, KeyManagementException, IOException {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
    //URL console = new URL("https://www.google.com/accounts/LoginAuth?continue=http%3A%2F%2Fwww.google.cn%2F&hl=zh-CN");
    URL console = new URL(url);
    String postData = from;
    HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
    conn.setSSLSocketFactory(sc.getSocketFactory());
    conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
    conn.setDoInput(true);
    conn.setDoOutput(true);
    BufferedOutputStream hurlBufOus = new BufferedOutputStream(conn.getOutputStream());
    //这里面已经将RequestMethod设置为POST.前面设置无效
    hurlBufOus.write(postData.getBytes());
    hurlBufOus.flush();
    conn.connect();
    InputStream ins = conn.getInputStream();
    BufferedOutputStream fileBufOus = new BufferedOutputStream(new FileOutputStream("c:/testWeb.html"));
    int read = 0;
    byte[] byteBuf = new byte[9412];
    while ((read = ins.read(byteBuf)) != -1) {
        fileBufOus.write(byteBuf, 0, read);
    }
    if (ins != null)
        ins.close();
    if (fileBufOus != null)
        fileBufOus.close();
}
Example 50
Project: hadoop-20-master  File: TestRaidFastCopy.java View source code
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    conf = new Configuration();
    conf.setInt("dfs.block.size", 1024);
    conf.setClass("fs.hdfs.impl", DistributedRaidFileSystem.class, FileSystem.class);
    cluster = new MiniDFSCluster(conf, 3, true, null);
    fs = cluster.getFileSystem();
    // Writing conf to disk so that the FastCopy tool picks it up.
    boolean flag = false;
    for (String dir : dirs) {
        if (new File(dir).exists()) {
            confFile = dir + fileName;
            String tmpConfFile = confFile + ".tmp";
            FileOutputStream out = new FileOutputStream(tmpConfFile);
            conf.writeXml(out);
            out.close();
            //rename the xml 
            (new File(tmpConfFile)).renameTo(new File(confFile));
            flag = true;
        }
    }
    if (!flag) {
        throw new Exception("Could not write conf file");
    }
}
Example 51
Project: domainmath-ide-master  File: DownloadTask.java View source code
/**
	 * Executed in background thread
	 */
@Override
protected Void doInBackground() throws Exception {
    try {
        HTTPDownloadUtil util = new HTTPDownloadUtil();
        util.downloadFile(downloadURL);
        // set file information on the GUI
        gui.setFileInfo(util.getFileName(), util.getContentLength());
        String saveFilePath = saveDirectory + File.separator + util.getFileName();
        InputStream inputStream = util.getInputStream();
        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        long totalBytesRead = 0;
        int percentCompleted = 0;
        long fileSize = util.getContentLength();
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            percentCompleted = (int) (totalBytesRead * 100 / fileSize);
            setProgress(percentCompleted);
        }
        outputStream.close();
        util.disconnect();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(gui, "Error downloading file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
        setProgress(0);
        cancel(true);
    }
    return null;
}