javatips.net counter

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: FileSystemFileStorage.java View source code
@Override
public void storeFileData(FileData fileData, InputStream in) {
    File f = new File(FilenameUtils.normalize(basePath + "/" + fileData.getPath() + "/" + fileData.getFileName()));
    if (!f.getParentFile().exists()) {
        f.getParentFile().mkdirs();
    }
    OutputStream out = null;
    try {
        out = new FileOutputStream(f);
        if (compress) {
            out = new GZIPOutputStream(out);
        }
        IOUtils.copy(in, out);
    } catch (Exception e) {
        LOG.error("Error storing file: " + e, e);
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}
Example 2
Project: trie4j-master  File: SaveLOUDSTrie.java View source code
public static void main(String[] args) throws Exception {
    TailPatriciaTrie trie1 = new TailPatriciaTrie();
    for (String s : new WikipediaTitles("data/jawiki-20120220-all-titles-in-ns0.gz")) {
        trie1.insert(s);
    }
    System.out.println(trie1.size() + "nodes.");
    SBVConcatTailArrayBuilder tailArray = new SBVConcatTailArrayBuilder(trie1.size());
    TailLOUDSTrie trie = new TailLOUDSTrie(trie1, tailArray);
    System.out.println(trie.size() + "nodes.");
    trie.freeze();
    OutputStream os = new FileOutputStream("louds.dat");
    try {
        ObjectOutputStream oos = new ObjectOutputStream(os);
        trie.writeExternal(oos);
        oos.flush();
    } finally {
        os.close();
    }
    os = new FileOutputStream("louds-bv.dat");
    try {
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(trie.getBvTree());
        oos.flush();
    } finally {
        os.close();
    }
    os = new FileOutputStream("louds-labels.dat");
    try {
        DataOutputStream dos = new DataOutputStream(os);
        for (char c : trie.getLabels()) {
            dos.writeChar(c);
        }
        dos.flush();
    } finally {
        os.close();
    }
    os = new FileOutputStream("louds-tails.dat");
    try {
        ObjectOutputStream dos = new ObjectOutputStream(os);
        dos.writeObject(tailArray);
        dos.flush();
    } finally {
        os.close();
    }
    os = new FileOutputStream("louds-tailIndex.dat");
    try {
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(tailArray);
        oos.flush();
    } finally {
        os.close();
    }
    os = new FileOutputStream("louds-term.dat");
    try {
        ObjectOutputStream dos = new ObjectOutputStream(os);
        dos.writeObject(trie.getTerm());
        dos.flush();
    } finally {
        os.close();
    }
}
Example 3
Project: ARTPart-master  File: FileDescriptorTest.java View source code
public void test_sync() throws IOException {
    File f = File.createTempFile("FileDescriptorText", "txt");
    FileOutputStream fos = null;
    FileInputStream fis = null;
    RandomAccessFile raf = null;
    try {
        fos = new FileOutputStream(f.getAbsolutePath());
        fos.write("Test String".getBytes(StandardCharsets.US_ASCII));
        fis = new FileInputStream(f.getPath());
        FileDescriptor fd = fos.getFD();
        fd.sync();
        int length = "Test String".length();
        assertEquals(length, fis.available());
        // Regression test for Harmony-1494
        fd = fis.getFD();
        fd.sync();
        assertEquals(length, fis.available());
        raf = new RandomAccessFile(f, "r");
        fd = raf.getFD();
        fd.sync();
    } finally {
        if (fos != null) {
            fos.close();
        }
        if (fis != null) {
            fis.close();
        }
        if (raf != null) {
            raf.close();
        }
    }
}
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: ExtractDataset.java View source code
public static void main(String[] args) throws Exception {
    // database connection
    Class.forName("com.mysql.jdbc.Driver");
    Connection jdbcConnection = DriverManager.getConnection("jdbc:mysql://127.0.0.1/ehour_08", "root", "root");
    IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
    QueryDataSet partialDataSet = new QueryDataSet(connection);
    // take note of the order to prevent FK constraint violation when re-inserting
    //        partialDataSet.addTable("user_department");
    //        partialDataSet.addTable("user");
    //        partialDataSet.addTable("user_role");
    //        partialDataSet.addTable("user_to_userrole");
    //        partialDataSet.addTable("customer");
    //        partialDataSet.addTable("project");
    //        partialDataSet.addTable("project_assignment_type");
    //        partialDataSet.addTable("project_assignment");
    //        partialDataSet.addTable("timesheet_entry");
    //        partialDataSet.addTable("timesheet_comment");
    //        partialDataSet.addTable("mail_type");
    //        partialDataSet.addTable("mail_log");
    //        partialDataSet.addTable("mail_log_assignment");
    partialDataSet.addTable("AUDIT");
    FlatXmlDataSet.write(partialDataSet, new FileOutputStream("src/test/resources/test-dataset-20081112.xml"));
    System.out.println("Dataset written");
}
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: UsingFontFactory.java View source code
/**
	 * Special rendering of Chunks.
	 * 
	 * @param args no arguments needed here
	 */
public static void main(String[] args) {
    System.out.println("Fonts in the FontFactory");
    // step 1: creation of a document-object
    Document document = new Document();
    try {
        // step 2:
        // we create a writer that listens to the document
        PdfWriter.getInstance(document, new FileOutputStream("FontFactory.pdf"));
        // step 3: we open the document
        document.open();
        // step 4:
        String name;
        Paragraph p = new Paragraph("Font Families", FontFactory.getFont(FontFactory.HELVETICA, 16f));
        document.add(p);
        FontFactory.registerDirectories();
        TreeSet families = new TreeSet(FontFactory.getRegisteredFamilies());
        int c = 0;
        for (Iterator i = families.iterator(); i.hasNext() && c < 15; ) {
            name = (String) i.next();
            p = new Paragraph(name);
            document.add(p);
            c++;
        }
        document.newPage();
        String quick = "quick brown fox jumps over the lazy dog";
        p = new Paragraph("Fonts", FontFactory.getFont(FontFactory.HELVETICA, 16f));
        for (Iterator i = families.iterator(); i.hasNext() && c > 0; ) {
            name = (String) i.next();
            p = new Paragraph(name);
            document.add(p);
            try {
                p = new Paragraph(quick, FontFactory.getFont(name, BaseFont.WINANSI, BaseFont.EMBEDDED));
                document.add(p);
            } catch (Exception e) {
                document.add(new Paragraph(e.getMessage()));
            }
            c--;
        }
    } 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: JarExtractor.java View source code
public static void extractFile(File dest, JarInputStream jarIS, JarEntry entry) throws IOException {
    File out = new File(dest, entry.getName());
    File parentDirectory = new File(out.getParent());
    if (!parentDirectory.exists() && !parentDirectory.mkdirs()) {
        Logger.logError("Cannot create dir: " + parentDirectory);
    }
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    byte buf[] = new byte[2048];
    try {
        fos = new FileOutputStream(out);
        bos = new BufferedOutputStream(fos);
        int num;
        while ((num = jarIS.read(buf, 0, 2048)) != -1) {
            bos.write(buf, 0, num);
        }
    } finally {
        FileUtil.cleanupStream(bos);
        FileUtil.cleanupStream(fos);
    }
}
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: LuaC.java View source code
public static void main(String[] args) throws FileNotFoundException, IOException {
    if (args.length < 2) {
        System.err.println("Not enough arguments");
        System.err.println("Syntax: java LuaC <input.lua> <output.lbc>");
        System.exit(1);
    }
    File input = new File(args[0]);
    System.out.println("Input: " + input.getCanonicalPath());
    File output = new File(args[1]);
    System.out.println("Output: " + output.getCanonicalPath());
    LuaTable table = new LuaTableImpl();
    LuaClosure closure = LuaCompiler.loadis(new FileInputStream(input), input.getName(), table);
    closure.prototype.dump(new FileOutputStream(output));
}
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: Executor.java View source code
public void exists(byte[] data) {
    if (data == null) {
        if (child != null) {
            System.out.println("Killing process");
            child.destroy();
            try {
                child.waitFor();
            } catch (InterruptedException e) {
            }
        }
        child = null;
    } else {
        if (child != null) {
            System.out.println("Stopping child");
            child.destroy();
            try {
                child.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream fos = new FileOutputStream(filename);
            fos.write(data);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            System.out.println("Starting child");
            child = Runtime.getRuntime().exec(exec);
            new StreamWriter(child.getInputStream(), System.out);
            new StreamWriter(child.getErrorStream(), System.err);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
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: AppSender.java View source code
private void shareFileViaBluetooth(String pathToFile) {
    Log.v(LOGTAG, "in shareFileViaBluetooth");
    String tempFileName = "temp.jpg";
    try {
        FileOutputStream fos = applicationContext.openFileOutput(tempFileName, Context.MODE_WORLD_READABLE);
        FileInputStream fin = new FileInputStream(pathToFile);
        byte[] buffer = new byte[4096];
        long total = 0L;
        int read = 0;
        while ((read = fin.read(buffer)) != -1) {
            fos.write(buffer, 0, read);
            total += read;
        }
        fin.close();
        fos.close();
        File tempFile = applicationContext.getFileStreamPath(tempFileName);
        tempFile.setReadable(true);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        //intent.setType("application/vnd.android.package-archive");
        intent.setType("image/jpeg");
        intent.setComponent(new ComponentName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity"));
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        applicationContext.startActivity(intent);
        Log.v(LOGTAG, "finish shareFileViaBluetooth");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.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: Downloader.java View source code
public void download(String inStrUrl, File outputFile) throws OpenEditException {
    FileOutputStream out = null;
    InputStream in = null;
    try {
        URL url = new URL(inStrUrl);
        URLConnection con = url.openConnection();
        //this helps prevent 403 errors.
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;     rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
        con.setUseCaches(false);
        con.connect();
        //*** create new output file
        //*** make a growable storage area to read into 
        outputFile.getParentFile().mkdirs();
        out = new FileOutputStream(outputFile);
        //*** read in url connection stream into input stream
        in = con.getInputStream();
        //*** fill output stream
        new OutputFiller().fill(in, out);
    } catch (Exception ex) {
        throw new OpenEditException(ex);
    } finally {
        //*** close output stream
        FileUtils.safeClose(out);
        //*** close input stream
        FileUtils.safeClose(in);
    }
}
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: ViewSamTest.java View source code
/**
     * Confirm that ViewSam retains whatever version number was in the input header.
     */
@Test
public void testHeaderVersion() throws Exception {
    final String oldVersionHeader = "@HD\tVN:1.3\tSO:unsorted";
    final File inputSam = File.createTempFile("ViewSamTest.input.", ".sam");
    inputSam.deleteOnExit();
    final AsciiWriter writer = new AsciiWriter(new FileOutputStream(inputSam));
    writer.write(oldVersionHeader);
    writer.write("\n");
    writer.close();
    final File viewSamOutputFile = File.createTempFile("ViewSamTest.output.", ".sam");
    viewSamOutputFile.deleteOnExit();
    final ViewSam viewSam = new ViewSam();
    viewSam.INPUT = inputSam;
    final PrintStream viewSamPrintStream = new PrintStream(viewSamOutputFile);
    // TODO - Should switch over to using invocation via new PicardCommandLine() - BUT the test here is accessing class members directly.
    Assert.assertEquals(viewSam.writeSamText(viewSamPrintStream), 0);
    viewSamPrintStream.close();
    final LineReader viewSamInputReader = new BufferedLineReader(new FileInputStream(viewSamOutputFile));
    Assert.assertEquals(viewSamInputReader.readLine(), oldVersionHeader);
}
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;
}
Example 52
Project: edx-app-android-master  File: SaveUriToFileTask.java View source code
public Uri call() throws Exception {
    if ("file".equals(uri.getScheme())) {
        // URI already points to a file
        return uri;
    }
    {
        final Uri fileUri = getFileUriFromMediaStoreUri(getContext(), uri);
        if (null != fileUri) {
            // URI was successfully resolved to a file
            return fileUri;
        }
    }
    // URI does not point to a file; Download/copy it to a temporary file.
    final File outputFile = new File(context.getExternalCacheDir(), "cropped-image" + System.currentTimeMillis() + ".jpg");
    final InputStream inputStream = context.getContentResolver().openInputStream(uri);
    try {
        final FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        try {
            IOUtils.copy(inputStream, fileOutputStream);
        } finally {
            fileOutputStream.close();
        }
    } finally {
        inputStream.close();
    }
    return Uri.fromFile(outputFile);
}
Example 53
Project: turmeric-eclipse-master  File: ZipExtractor.java View source code
public void extract(String zipFileLocation, String dest) {
    File temp = new File(dest);
    FileOutputStream os = null;
    temp.mkdirs();
    FileInputStream zipfile = null;
    try {
        zipfile = new FileInputStream(zipFileLocation);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        ZipInputStream instream = new ZipInputStream(zipfile);
        ZipEntry entry = instream.getNextEntry();
        while (instream.available() != 0) {
            byte[] b = new byte[1024];
            int i = 0;
            int index = entry.getName().lastIndexOf("/");
            if (!entry.isDirectory()) {
                if (index != -1) {
                    String dir = entry.getName().substring(0, index);
                    String filename = entry.getName().substring(index + 1);
                    File createDir = new File(temp, dir);
                    createDir.mkdirs();
                    File file = new File(createDir, filename);
                    file.createNewFile();
                    os = new FileOutputStream(file);
                } else {
                    File file = new File(temp, entry.getName());
                    file.createNewFile();
                    os = new FileOutputStream(file);
                }
                while (i != -1) {
                    i = instream.read(b, 0, 1024);
                    if (i > -1)
                        os.write(b, 0, i);
                    ;
                }
            } else {
                File file = new File(temp, entry.getName());
                if (!file.exists()) {
                    file.mkdirs();
                }
            }
            instream.closeEntry();
            entry = instream.getNextEntry();
            if (os != null)
                os.close();
        }
        if (instream != null)
            instream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 54
Project: compomics-utilities-master  File: DownloadingUtil.java View source code
/**
     * Download a file from a URL.
     * 
     * @param parent the parent
     * @param url the URL to download
     * @param outputFile the output file
     * @param progressDialog the progress dialog
     * @return true if the downloading worked
     * @throws IOException if an exception occurs
     */
public static boolean downloadFileFromURL(ImportSequencesFromUniprotDialog parent, URL url, File outputFile, ProgressDialogX progressDialog) throws IOException {
    //start the downloading and update the dialog every read?
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
        in = new BufferedInputStream(url.openStream());
        fout = new FileOutputStream(outputFile);
        final byte data[] = new byte[1024];
        int totalCount = 0;
        int count;
        while ((count = in.read(data, 0, 1024)) != -1) {
            if (!parent.isCanceled() & !progressDialog.isRunCanceled()) {
                fout.write(data, 0, count);
                totalCount += count;
                progressDialog.setSecondaryProgressText("Downloaded " + totalCount + " bytes");
            } else {
                return false;
            }
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
        progressDialog.setSecondaryProgressText("");
        progressDialog.resetSecondaryProgressCounter();
    }
    return true;
}
Example 55
Project: DrakkarKeel-master  File: XMLParser.java View source code
/**
     * Modifica el valor asociado al parámetro especificado
     *
     * @param parametername nombre del parámetro
     * @param newvalue      nuevo valor
     *
     * @return true si se pudo actualizar el valor, false en caso contrario
     */
public boolean setValue(String parametername, String newvalue) {
    org.jdom.Element element = getElement(parametername);
    if (element != null) {
        element.setAttribute("value", newvalue);
        try {
            org.jdom.output.XMLOutputter out = new org.jdom.output.XMLOutputter();
            try (java.io.FileOutputStream file = new java.io.FileOutputStream(configurationfile)) {
                out.output(xmldoc, file);
                file.flush();
            }
            //out.output(xmldoc, System.out);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}
Example 56
Project: openjdk8-jdk-master  File: ProcessAttachDebuggee.java View source code
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.");
}
Example 57
Project: openmap-master  File: SavePropertiesMenuItem.java View source code
public void actionPerformed(ActionEvent ae) {
    //Collect properties
    if (mapHandler == null) {
        if (Debug.debugging("menu")) {
            Debug.error("SavePropertiesMenuItem: no Map Handler to use");
        }
        return;
    }
    FileDialog fd = new FileDialog(new Frame(), "Saving the map as Properties file...", FileDialog.SAVE);
    fd.setVisible(true);
    String fileName = fd.getFile();
    String dirName = fd.getDirectory();
    if (fileName == null) {
        Debug.message("savepropertiesmenuitem", "User did not select any file");
        return;
    }
    Debug.message("savepropertiesmenuitem", "User selected file " + dirName + File.separator + fileName);
    File file = new File(new File(dirName), fileName);
    FileOutputStream fos;
    PrintStream ps = null;
    try {
        fos = new FileOutputStream(file);
    }/*
         * In JDK 1.2, the FileOutputStream(File) constructor throws a
         * IOException, but in JDK1.3 it throws FileNotFoundException.
         * So in 1.2 it is insufficient to catch
         * FileNotFoundException, you need to catch IOException. But
         * in 1.3, catching FileNotFoundException is enough.
         */
     catch (IOException fnfe) {
        System.err.println(fnfe.getMessage());
        return;
    }
    ps = new PrintStream(fos);
    PropertyHandler.createOpenMapProperties(mapHandler, ps);
    ps.close();
}
Example 58
Project: SealBrowser-master  File: TestFileUtil.java View source code
public static void createNewHtmlFile(String name, String title, String body) throws IOException {
    File file = new File(name);
    if (!file.createNewFile()) {
        throw new IOException("File \"" + name + "\" already exists");
    }
    Writer writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        writer.write("<html><meta charset=\"UTF-8\" />" + "<head><title>" + title + "</title></head>" + "<body>" + (body != null ? body : "") + "</body>" + "</html>");
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
Example 59
Project: freemind-mmx-master  File: XmlExporter.java View source code
public void transForm(File xmlFile, File xsltFile, File resultFile) throws FileNotFoundException {
    // System.out.println("set source");
    Source xmlSource = new StreamSource(xmlFile);
    // System.out.println("set xsl");
    Source xsltSource = new StreamSource(xsltFile);
    // System.out.println("set result");
    Result result = new StreamResult(new FileOutputStream(resultFile));
    // create an instance of TransformerFactory
    try {
        // System.out.println("make transform instance");
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(xsltSource);
        trans.transform(xmlSource, result);
    } catch (Exception e) {
        freemind.main.Resources.getInstance().logException(e);
    }
    ;
    return;
}
Example 60
Project: yarn-comment-master  File: TestHarIndexParser.java View source code
protected void setUp() throws FileNotFoundException, IOException {
    LOG.info("TestHarIndexParser.setUp()");
    indexFile = File.createTempFile("harindex", ".tmp");
    indexFile.deleteOnExit();
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(indexFile), Charset.forName("UTF-8"));
    out.write("%2F dir 1282018162460+0+493+hadoop+hadoop 0 0 f1 f2 f3 f4\n");
    out.write("%2Ff1 file part-0 0 1024 1282018141145+1282018140822+420+hadoop+hadoop\n");
    out.write("%2Ff3 file part-0 2048 1024 1282018148590+1282018148255+420+hadoop+hadoop\n");
    out.write("%2Ff2 file part-0 1024 1024 1282018144198+1282018143852+420+hadoop+hadoop\n");
    out.write("%2Ff4 file part-1 0 1024000 1282018162959+1282018162460+420+hadoop+hadoop\n");
    out.flush();
    out.close();
}
Example 61
Project: flink-master  File: BinaryInputFormatTest.java View source code
@Test
public void testCreateInputSplitsWithOneFile() throws IOException {
    // create temporary file with 3 blocks
    final File tempFile = File.createTempFile("binary_input_format_test", "tmp");
    tempFile.deleteOnExit();
    final int blockInfoSize = new BlockInfo().getInfoSize();
    final int blockSize = blockInfoSize + 8;
    final int numBlocks = 3;
    FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
    for (int i = 0; i < blockSize * numBlocks; i++) {
        fileOutputStream.write(new byte[] { 1 });
    }
    fileOutputStream.close();
    final Configuration config = new Configuration();
    config.setLong("input.block_size", blockSize + 10);
    final BinaryInputFormat<Record> inputFormat = new MyBinaryInputFormat();
    inputFormat.setFilePath(tempFile.toURI().toString());
    inputFormat.setBlockSize(blockSize);
    inputFormat.configure(config);
    FileInputSplit[] inputSplits = inputFormat.createInputSplits(numBlocks);
    Assert.assertEquals("Returns requested numbers of splits.", numBlocks, inputSplits.length);
    Assert.assertEquals("1. split has block size length.", blockSize, inputSplits[0].getLength());
    Assert.assertEquals("2. split has block size length.", blockSize, inputSplits[1].getLength());
    Assert.assertEquals("3. split has block size length.", blockSize, inputSplits[2].getLength());
}
Example 62
Project: MyFramework-master  File: AgentPaymentBatchFileGenerator.java View source code
public static void main(String[] args) {
    String templateFile = "ccb-c.ftl";
    String fileName = "E:/template/RPT_ORG_SUMMARY" + DateUtil.formatCurrDateTime(DateUtil.DF_YMDHMS) + ".txt";
    Map model = new HashMap();
    String date = DateUtil.formatCurrDateTime(DateUtil.DF_YYYY_MM_DD);
    model.put("tlAccountNo", "100010001000");
    model.put("today", DateUtil.date2string(new Date()));
    List resultList = new ArrayList();
    AgentPaymentDetail paymentBatchDetail = new AgentPaymentDetail();
    paymentBatchDetail.setMerchantId("1000200912180001");
    paymentBatchDetail.setAccountName("name");
    paymentBatchDetail.setAccountNo("no");
    paymentBatchDetail.setAmount(10000L);
    paymentBatchDetail.setFee(888l);
    resultList.add(paymentBatchDetail);
    AgentPaymentDetail paymentBatchDetail1 = new AgentPaymentDetail();
    paymentBatchDetail.setMerchantId("1000200912180002");
    paymentBatchDetail1.setAccountName("name2");
    paymentBatchDetail1.setAccountNo("no2");
    paymentBatchDetail1.setAmount(8898l);
    paymentBatchDetail1.setFee(888l);
    resultList.add(paymentBatchDetail1);
    model.put("resultList", resultList);
    Writer writer = null;
    FileWriter fw = null;
    try {
        writer = new CharArrayWriter();
        Template template = getTemplate(templateFile);
        template.process(model, writer);
        writer.flush();
        File file = new File(fileName);
        file.delete();
        OutputStream os = new FileOutputStream(file);
        FileUtil.save(os, writer.toString().getBytes("utf-8"));
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != writer) {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != fw) {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 63
Project: rascal-master  File: SnakesAndLadders.java View source code
private void copyFile(URIResolverRegistry reg, ISourceLocation sourceRoot, ISourceLocation sourcePath, File targetRoot) throws IOException {
    File targetPath = new File(targetRoot, sourcePath.getPath().replace(sourceRoot.getPath(), ""));
    if (targetPath.getAbsolutePath().endsWith(".jv")) {
        String targetPathName = targetPath.getAbsolutePath();
        targetPath = new File(targetPathName.substring(0, targetPathName.length() - 3) + ".java");
    }
    targetPath.getParentFile().mkdirs();
    try (InputStream from = reg.getInputStream(sourcePath)) {
        try (OutputStream to = new FileOutputStream(targetPath)) {
            byte[] buffer = new byte[8 * 1024];
            int read;
            while ((read = from.read(buffer)) > 0) {
                to.write(buffer, 0, read);
            }
        } finally {
            targetPath.deleteOnExit();
        }
    }
}
Example 64
Project: openjdk-master  File: CanWriteSequence.java View source code
private static void test(final ImageWriter writer) throws Exception {
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new FileOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    final IIOMetadata data = writer.getDefaultStreamMetadata(null);
    if (writer.canWriteSequence()) {
        writer.prepareWriteSequence(data);
    } else {
        try {
            writer.prepareWriteSequence(data);
            throw new RuntimeException("UnsupportedOperationException was not thrown");
        } catch (final UnsupportedOperationException ignored) {
        }
    }
    writer.dispose();
    ios.close();
}
Example 65
Project: js-android-app-master  File: PermanentDatabase.java View source code
public ResourceDatabase prepare() {
    File originalFile = resourceDatabase.getFile();
    String copyResourceName = originalFile.getName() + "-copy";
    File copyFile = new File(originalFile.getParentFile(), copyResourceName);
    InputStream in = resourceDatabase.getInputStream();
    try {
        OutputStream out = new FileOutputStream(copyFile);
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        ResourceDatabase resourceDatabase = ResourceDatabase.get(copyResourceName);
        return resourceDatabase;
    } catch (FileNotFoundException e) {
        throw new RuntimeException();
    } catch (IOException e) {
        throw new RuntimeException();
    }
}
Example 66
Project: erlide-master  File: SaveAction.java View source code
@Override
public void run() {
    final StringBuilder statName = new StringBuilder();
    statName.append("cov_").append(StatsTreeModel.getInstance().getTimestamp());
    final IPath location = Activator.getDefault().getStateLocation().append(DIR_NAME);
    final File dir = location.toFile();
    if (!dir.exists() && !dir.mkdir()) {
        CoverageHelper.reportError("Can not save results!");
        return;
    }
    // open input dialog
    final InputDialog nameDialog = new InputDialog(shell, "Saving coverage results", "Enter the name for saving coverage results", statName.toString(), new IInputValidator() {

        @Override
        public String isValid(final String newText) {
            final String[] names = dir.list();
            if (newText == null || newText.length() < 1) {
                return "Name too short";
            }
            for (final String name : names) {
                if (name.equals(newText)) {
                    return "Results file with the same name already exists";
                }
            }
            return null;
        }
    });
    nameDialog.open();
    String name = "";
    if (nameDialog.getReturnCode() == Window.OK) {
        name = nameDialog.getValue();
    } else {
        return;
    }
    //
    log.info(location);
    log.info(name);
    try (final ObjectOutputStream objOutStream = new ObjectOutputStream(new FileOutputStream(location.append(name).toString()))) {
        objOutStream.writeObject(StatsTreeModel.getInstance());
    } catch (final FileNotFoundException e) {
        log.error("Error while openning stream");
        ErlLogger.error(e);
        CoverageHelper.reportError("Cannot save results");
    } catch (final IOException e) {
        log.error("Error while writing to a file");
        ErlLogger.error(e);
        CoverageHelper.reportError("Cannot save results");
    }
}
Example 67
Project: wso2-synapse-master  File: VFSClient.java View source code
protected void send(byte[] message) throws Exception {
    // Create the file atomically (using move/rename) to avoid problems with the
    // listener starting to read the file too early.
    File tmpFile = new File(requestFile.getParent(), "." + requestFile.getName() + ".tmp");
    log.debug("Writing message to temporary file " + tmpFile);
    OutputStream out = new FileOutputStream(tmpFile);
    out.write(message);
    out.close();
    log.debug("Moving " + tmpFile + " to " + requestFile);
    if (!tmpFile.renameTo(requestFile)) {
        throw new IOException("Unable to rename " + tmpFile + " to " + requestFile);
    }
    log.debug("Done.");
}
Example 68
Project: Technomap-master  File: ExportDisplayAction.java View source code
/**
     * Shows the image export dialog and processes the results.
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
public void actionPerformed(ActionEvent evt) {
    // lazy initialization
    if (chooser == null)
        init();
    // open image save dialog
    File f = null;
    scaler.setImage(display.getOffscreenBuffer());
    int returnVal = chooser.showSaveDialog(display);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        f = chooser.getSelectedFile();
    } else {
        return;
    }
    String format = ((SimpleFileFilter) chooser.getFileFilter()).getExtension();
    String ext = IOLib.getExtension(f);
    if (!format.equals(ext)) {
        f = new File(f.toString() + "." + format);
    }
    double scale = scaler.getScale();
    // save image
    boolean success = false;
    try {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
        System.out.print("Saving image " + f.getName() + ", " + format + " format...");
        success = display.saveImage(out, format, scale);
        out.flush();
        out.close();
        System.out.println("\tDONE");
    } catch (Exception e) {
        success = false;
    }
    // show result dialog on failure
    if (!success) {
        JOptionPane.showMessageDialog(display, "Error Saving Image!", "Image Save Error", JOptionPane.ERROR_MESSAGE);
    }
}
Example 69
Project: android_platform_libcore-master  File: GenericSignatureFormatErrorTest.java View source code
@AndroidOnly("Uses Android specific class dalvik.system.DexFile " + "for loading classes.")
@SideEffect("strange issue (exception: 'could not open dex file', " + "dalvikvm: 'waitpid failed' log msg  - only occurs when @SideEffect is removed " + "and this test is run via running tests.luni.AllTestsLang TestSuite")
public void test_signatureFormatError() throws Exception {
    /*
         * dex1.bytes is a jar file with a classes.dex in it.
         * the classes.dex was javac'ed, dx'ed and patched
         * with the following java file:
         *
         * package demo;
         *  public class HelloWorld<U> {
         *      public HelloWorld(U t) {}
         *  }
         *
         * patch:
         * the string constant (class generics signature string)
         *  "<U:" was changed to "<<:"
         *
         */
    File tf = File.createTempFile("classes", ".dex");
    // System.out.println("GenericSignatureFormatErrorTest:" +
    //         tf.getAbsolutePath() + ", canRead: " + tf.canRead() +
    //         ", canWrite: "+tf.canWrite());
    InputStream is = this.getClass().getResourceAsStream("dex1.bytes");
    assertNotNull(is);
    OutputStream fos = new FileOutputStream(tf);
    copy(is, fos);
    fos.flush();
    fos.close();
    //System.out.println("file length:"+tf.length());
    try {
        // Was:
        // DexFile df = new DexFile(tf);
        // Class clazz = df.loadClass("demo/HelloWorld", this.getClass().getClassLoader());
        ClassLoader cl = Support_ClassLoader.getInstance(tf.toURL(), getClass().getClassLoader());
        Class clazz = cl.loadClass("demo/HelloWorld");
        TypeVariable[] tvs = clazz.getTypeParameters();
        fail("expecting a GenericSignatureFormatError");
    // for (TypeVariable tv : tvs) {
    //     System.out.println("tv:"+tv.toString());
    // }
    } catch (GenericSignatureFormatError gsfe) {
    }
}
Example 70
Project: JPaxos-master  File: ConfigurationTest.java View source code
@Test
public void shouldLoadFromFile() throws FileNotFoundException, IOException {
    Properties properties = new Properties();
    properties.put("process.0", "localhost:2000:3000");
    properties.put("process.1", "localhost:2001:3001");
    properties.put("process.2", "localhost:2002:3002");
    properties.put("integer", "5");
    properties.put("boolean", "true");
    properties.put("string", "hello world");
    File tempFile = File.createTempFile("paxos", "");
    FileOutputStream outputStream = new FileOutputStream(tempFile);
    properties.store(outputStream, "");
    outputStream.close();
    Configuration configuration = new Configuration(tempFile.getAbsolutePath());
    assertEquals(3, configuration.getN());
    assertEquals("localhost", configuration.getProcess(0).getHostname());
    assertEquals(2000, configuration.getProcess(0).getReplicaPort());
    assertEquals(3000, configuration.getProcess(0).getClientPort());
    assertEquals(5, configuration.getIntProperty("integer", 3));
    assertEquals(true, configuration.getBooleanProperty("boolean", false));
    assertEquals("hello world", configuration.getProperty("string", "default"));
}
Example 71
Project: android-voip-service-master  File: Ring.java View source code
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ring);
    try {
        try {
            System.loadLibrary("ring");
        } catch (UnsatisfiedLinkError e) {
            Log.e("mediastreamer2", "cannot load libring.so, did you compile SDK with ndk-build RING=yes ", e);
        }
        final File lFileToPlay = getFileStreamPath("oldphone_mono.wav");
        if (!lFileToPlay.exists()) {
            FileOutputStream lOutputStream = openFileOutput("oldphone_mono.wav", 0);
            InputStream lInputStream = getResources().openRawResource(R.raw.oldphone_mono);
            int readByte;
            while ((readByte = lInputStream.read()) != -1) {
                lOutputStream.write(readByte);
            }
            lOutputStream.flush();
            lOutputStream.close();
            lInputStream.close();
        }
        init();
        mWorkerThread = new Thread(new Runnable() {

            public void run() {
                play(lFileToPlay.getAbsolutePath());
                echo(44100);
            }
        }, "Worker Thread");
        mWorkerThread.start();
    } catch (Exception e) {
        Log.e("ring", "error", e);
    }
}
Example 72
Project: Eclipse-Postfix-Code-Completion-master  File: PersistentSpellDictionary.java View source code
/*
	 * @see org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellDictionary#addWord(java.lang.String)
	 */
@Override
public void addWord(final String word) {
    if (isCorrect(word))
        return;
    FileOutputStream fileStream = null;
    try {
        Charset charset = Charset.forName(getEncoding());
        //$NON-NLS-1$
        ByteBuffer byteBuffer = charset.encode(word + "\n");
        int size = byteBuffer.limit();
        final byte[] byteArray;
        if (byteBuffer.hasArray())
            byteArray = byteBuffer.array();
        else {
            byteArray = new byte[size];
            byteBuffer.get(byteArray);
        }
        fileStream = new FileOutputStream(fLocation.getPath(), true);
        // Encoding UTF-16 charset writes a BOM. In which case we need to cut it away if the file isn't empty
        int bomCutSize = 0;
        if (//$NON-NLS-1$
        !isEmpty() && "UTF-16".equals(charset.name()))
            bomCutSize = 2;
        fileStream.write(byteArray, bomCutSize, size - bomCutSize);
    } catch (IOException exception) {
        JavaPlugin.log(exception);
        return;
    } finally {
        try {
            if (fileStream != null)
                fileStream.close();
        } catch (IOException e) {
        }
    }
    hashWord(word);
}
Example 73
Project: RajawaliOpenAL-master  File: OpenAlBridge.java View source code
private static void retrieveFromAssets(Activity activity, String filename) throws IOException {
    InputStream is = activity.getAssets().open(filename);
    // Destination
    File outFile = new File(activity.getFilesDir(), filename);
    Log.i(TAG, "retrieveFromAssets( .. ) copying " + filename + " to " + outFile.getParent());
    FileOutputStream fos = new FileOutputStream(outFile);
    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer)) > 0) {
        fos.write(buffer, 0, length);
    }
    // Close the streams
    fos.flush();
    fos.close();
    is.close();
}
Example 74
Project: ecologylabFundamental-master  File: LoggingContextScope.java View source code
public synchronized void setUpOutputStreamWriter(String logFileName) throws IOException {
    String logFilesPath = (String) this.get(NIOLoggingServer.LOG_FILES_PATH);
    String fileName = logFilesPath + logFileName;
    File file = new File(fileName);
    String dirPath = file.getParent();
    if (dirPath != null) {
        Debug.println("dirPath = " + dirPath);
        File dir = new File(dirPath);
        if (!dir.exists()) {
            Debug.println("dirPath did not exist. create with mkdirs()");
            dir.mkdirs();
        }
    }
    Debug.println("attempting to use filename: " + fileName);
    // rename file until we are not overwriting an existing file
    if (file.exists()) // a little weird to do it this way, but the if is cheaper than
    {
        // potentially reallocating the String over and over
        String filename = file.getName();
        int dotIndex = filename.lastIndexOf('.');
        int i = 1;
        do {
            Debug.println(filename + " already exists.");
            String newFilename = (dotIndex > -1 ? filename.substring(0, dotIndex) + i + filename.substring(dotIndex) : filename + i);
            Debug.println("trying new filename = " + newFilename);
            i++;
            // we already took care of the parent directories
            // just need to make a new file w/ a new name
            file = new File(newFilename);
        } while (file.exists());
    }
    if (!file.createNewFile()) {
        throw new IOException("Could not create the logging file.");
    }
    Debug.println("Logging to file at: " + file.getAbsolutePath());
    FileOutputStream fos = new FileOutputStream(file, true);
    CharsetEncoder encoder = Charset.forName(NetworkingConstants.CHARACTER_ENCODING).newEncoder();
    outputStreamWriter = new OutputStreamWriter(fos, encoder);
}
Example 75
Project: android-libcore64-master  File: BufferedZipFileBenchmark.java View source code
@Override
protected void setUp() throws Exception {
    file = File.createTempFile(getClass().getName(), ".zip");
    file.deleteOnExit();
    Random random = new Random(0);
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
    byte[] data = new byte[8192];
    out.putNextEntry(new ZipEntry("entry.data"));
    int written = 0;
    while (written < compressedSize) {
        random.nextBytes(data);
        int toWrite = Math.min(compressedSize - written, data.length);
        out.write(data, 0, toWrite);
        written += toWrite;
    }
    out.close();
}
Example 76
Project: geotoolkit-master  File: ReferenceToFileConverter.java View source code
/**
     * [email protected]}
     *
     * @return File.
     */
@Override
public File convert(final Reference source, final Map<String, Object> params) throws UnconvertibleObjectException {
    File file;
    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = getInputStreamFromReference(source);
        final String fileName = UUID.randomUUID().toString();
        final String suffix = ".tmp";
        //Create a temp file
        file = File.createTempFile(fileName, suffix);
        out = new FileOutputStream(file);
        //copy
        byte buf[] = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.flush();
    } catch (MalformedURLException ex) {
        throw new UnconvertibleObjectException("Reference file invalid input : Malformed url", ex);
    } catch (IOException ex) {
        throw new UnconvertibleObjectException("Reference file invalid input : IO", ex);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
            throw new UnconvertibleObjectException("Reference file invalid input : IO", ex);
        }
    }
    return file;
}
Example 77
Project: xDrip-master  File: DatabaseUtil.java View source code
public static String saveSql(Context context) {
    try {
        final String databaseName = new Configuration.Builder(context).create().getDatabaseName();
        final String dir = getExternalDir();
        makeSureDirectoryExists(dir);
        final StringBuilder sb = new StringBuilder();
        sb.append(dir);
        sb.append("/export");
        sb.append(DateFormat.format("yyyyMMdd-kkmmss", System.currentTimeMillis()));
        sb.append(".sqlite");
        final String filename = sb.toString();
        final File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) {
            final File currentDB = context.getDatabasePath(databaseName);
            final File backupDB = new File(filename);
            if (currentDB.exists()) {
                final FileInputStream srcStream = new FileInputStream(currentDB);
                final FileChannel src = srcStream.getChannel();
                final FileOutputStream destStream = new FileOutputStream(backupDB);
                final FileChannel dst = destStream.getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                srcStream.close();
                dst.close();
                destStream.close();
            }
        }
        return filename;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
Example 78
Project: javainstaller-master  File: Download.java View source code
public void run() {
    InputStream input = null;
    OutputStream output = null;
    URLConnection connection = null;
    HttpURLConnection httpconnection = null;
    try {
        connection = url.openConnection();
        connection.connect();
        if (connection instanceof HttpURLConnection) {
            httpconnection = (HttpURLConnection) connection;
            // instead of the file
            if (httpconnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                final String error = "Server returned HTTP " + httpconnection.getResponseCode() + " " + httpconnection.getResponseMessage();
                handler.post(new Error(new Exception(error), ctx));
                System.out.println("Server returned HTTP " + httpconnection.getResponseCode() + " " + httpconnection.getResponseMessage());
            }
        }
        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();
        // download the file
        input = connection.getInputStream();
        output = new FileOutputStream(path);
        final byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data, 0, 1024)) != -1) {
            total += count;
            final int percent = (int) (total * 100 / fileLength);
            final String status = total / 1024 + "/" + fileLength / 1024 + "kb  " + percent + "/100%";
            handler.post(new Runnable() {

                @Override
                public void run() {
                    progress.setProgress(percent);
                    tv.setText(status);
                }
            });
            output.write(data, 0, count);
        }
        input.close();
        output.close();
    //progress.dismiss();
    } catch (Exception e) {
        e.printStackTrace();
        handler.post(new Error(e, ctx));
    }
}
Example 79
Project: GlowstonePlusPlus-master  File: LibraryManager.java View source code
private void download(String group, String library, String version) {
    // check if we already have it
    File file = new File(directory, library + "-" + version + ".jar");
    if (!file.exists()) {
        // download it
        GlowServer.logger.info("Downloading " + library + " " + version + "...");
        try {
            URL downloadUrl = new URL(repository + group.replace('.', '/') + "/" + library + "/" + version + "/" + library + "-" + version + ".jar");
            try (ReadableByteChannel input = Channels.newChannel(downloadUrl.openStream());
                FileOutputStream output = new FileOutputStream(file)) {
                output.getChannel().transferFrom(input, 0, Long.MAX_VALUE);
            }
        } catch (IOException e) {
            GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + " " + version, e);
            return;
        }
    }
    // hack it onto the classpath
    URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    try {
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        method.setAccessible(true);
        method.invoke(sysLoader, file.toURI().toURL());
    } catch (ReflectiveOperationExceptionMalformedURLException |  e) {
        GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e);
    }
}
Example 80
Project: i2p.android.base-master  File: AddressbookSettingsActivity.java View source code
private boolean save() {
    //
    String content = text_content_subscriptions.getText().toString();
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(i2pDir);
        byte[] contentInBytes = content.getBytes();
        out.write(contentInBytes);
        out.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
    }
}
Example 81
Project: geotools-old-master  File: PropertyDumper.java View source code
public static void main(String[] args) throws Exception {
    String filename = "/tmp/wkt.properties";
    Properties diff = new Properties();
    String compare = null;
    if (args.length > 0) {
        filename = args[0];
    }
    if (args.length > 1) {
        File file = new File(args[1]);
        if (file.exists()) {
            InputStream in = new FileInputStream(file);
            diff.load(in);
        }
    }
    FileOutputStream out = new FileOutputStream(filename);
    Writer writer = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
    writer.append("Generate from EPSG database version " + ThreadedHsqlEpsgFactory.VERSION);
    Properties props = new Properties();
    for (String code : CRS.getSupportedCodes("EPSG")) {
        try {
            CoordinateReferenceSystem crs = CRS.decode("EPSG:" + code, true);
            // use toString, it's more lenient that toWKT
            String wkt = crs.toString().replaceAll("\n", "").replaceAll("  ", "");
            // make sure we can parse back what we generated
            CRS.parseWKT(wkt);
            props.put(code, wkt);
            diff.remove(code);
        } catch (Exception e) {
            System.out.println("#" + code + " -> " + e.getMessage());
        }
    }
    props.store(out, "Generated from EPSG database version " + ThreadedHsqlEpsgFactory.VERSION);
    if (!diff.isEmpty()) {
        diff.store(out, "Extra Definitions Supplied from Community");
    }
    out.close();
}
Example 82
Project: FallUML2013-master  File: DownloadZipfile.java View source code
/**
     * Compress
     * @param targetPath
     * @param output - the output filename  
     * @throws IOException
     */
public void downloadZipfileProcessor(String targetPath, String output) throws IOException {
    File targetFile = new File(targetPath);
    if (!targetFile.isFile() && !targetFile.isDirectory()) {
        throw new IOException("File not found");
    }
    if (!(StringUtils.substringAfterLast(output, ".")).equalsIgnoreCase("zip")) {
        throw new IOException("Check the output filename extension(.zip)");
    }
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    ZipOutputStream zos = null;
    try {
        fos = new FileOutputStream(output);
        bos = new BufferedOutputStream(fos);
        zos = new ZipOutputStream(bos);
        zos.setLevel(COMPRESSION_LEVEL);
        zipEntry(targetFile, targetPath, zos);
        zos.finish();
        zos.close();
    } catch (IOException ex) {
    } finally {
        if (zos != null) {
            zos.close();
        }
        if (bos != null) {
            bos.close();
        }
        if (fos != null) {
            fos.close();
        }
    }
}
Example 83
Project: dcache-master  File: dirLister.java View source code
public void doIt() {
    try {
        File sourceDir = new File(source);
        if (sourceDir.exists() && sourceDir.isDirectory() && sourceDir.canRead()) {
            File destFile = new File(dest);
            if (!destFile.exists() || (destFile.isFile() && destFile.canWrite())) {
                OutputStreamWriter destWriter = new OutputStreamWriter(new FileOutputStream(destFile), "UTF-8");
                ds = new dataStore(sourceDir, destFile, recurse, doMath);
                lister = new XMLLister(destWriter);
                System.out.println("Processing directory " + ds.getDir());
                System.out.println();
                doWrite(ds.getDir());
                lister.close();
            } else {
                System.out.println("A problem occurred with the destination file.");
            }
        } else {
            System.out.println("A problem occurred with the source directory.");
        }
    } catch (IOException e) {
        System.out.println("Error!: " + e.toString());
        System.out.println();
    }
}
Example 84
Project: HDP-2.2-Patched-master  File: OfflineEditsVisitorFactory.java View source code
/**
   * Factory function that creates an EditsVisitor object
   *
   * @param filename              output filename
   * @param processor             type of visitor to create 
   * @param printToScreen         parameter passed to visitor constructor
   *
   * @return EditsVisitor for appropriate output format (binary, xml, etc.)
   */
public static OfflineEditsVisitor getEditsVisitor(String filename, String processor, boolean printToScreen) throws IOException {
    if (processor.toLowerCase().equals("binary")) {
        return new BinaryEditsVisitor(filename);
    }
    OfflineEditsVisitor vis;
    OutputStream fout = new FileOutputStream(filename);
    OutputStream out = null;
    try {
        if (!printToScreen) {
            out = fout;
        } else {
            OutputStream outs[] = new OutputStream[2];
            outs[0] = fout;
            outs[1] = System.out;
            out = new TeeOutputStream(outs);
        }
        if (processor.toLowerCase().equals("xml")) {
            vis = new XmlEditsVisitor(out);
        } else if (processor.toLowerCase().equals("stats")) {
            vis = new StatisticsEditsVisitor(out);
        } else {
            throw new IOException("Unknown proccesor " + processor + " (valid processors: xml, binary, stats)");
        }
        out = fout = null;
        return vis;
    } finally {
        IOUtils.closeStream(fout);
        IOUtils.closeStream(out);
    }
}
Example 85
Project: earthsci-master  File: CopyPrefs.java View source code
public static void copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}
Example 86
Project: firetweet-master  File: ProfilingUtil.java View source code
public static void profile(final Context context, final String name, final String text) {
    if (context == null)
        return;
    final SharedPreferences prefs = context.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    if (!prefs.getBoolean(Constants.KEY_USAGE_STATISTICS, false))
        return;
    final String filename = name + ".csv";
    new Thread() {

        @Override
        public void run() {
            try {
                final FileOutputStream fos = context.openFileOutput(filename, Context.MODE_APPEND);
                if (fos == null)
                    return;
                final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
                bw.write("[" + System.currentTimeMillis() + "], " + text + "\n");
                bw.flush();
                fos.close();
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }

        ;
    }.start();
}
Example 87
Project: android-ePub-Library-master  File: BBBEPubCoverTest.java View source code
private String extractFile(String resource) throws Exception {
    File fileOutput = new File("test.epub");
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resource);
    OutputStream outputStream = new FileOutputStream(fileOutput);
    // transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    // Close the streams
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    return fileOutput.getAbsolutePath();
}
Example 88
Project: schach-master  File: TinyVM.java View source code
public void start(String classpath, String[] classes, boolean all, String output, boolean bigEndian, boolean debug, int options, boolean verbose) throws TinyVMException {
    // verbosity
    for (ToolProgressMonitor monitor : _monitors) {
        monitor.setVerbose(verbose);
    }
    //((CLIToolProgressMonitor) getProgressMonitor()).setVerbose(verbose);
    OutputStream stream = null;
    try {
        stream = output == null ? (OutputStream) System.out : (OutputStream) new FileOutputStream(output);
        link(classpath, classes, all, stream, bigEndian, options, debug);
    } catch (FileNotFoundException e) {
        throw new TinyVMException(e.getMessage(), e);
    } finally {
        if (stream instanceof FileOutputStream) {
            try {
                stream.close();
            } catch (IOException e) {
                throw new TinyVMException(e);
            }
        }
    }
}
Example 89
Project: RedReader-master  File: RedReader.java View source code
public void uncaughtException(Thread thread, Throwable t) {
    try {
        t.printStackTrace();
        File dir = Environment.getExternalStorageDirectory();
        if (dir == null) {
            dir = Environment.getDataDirectory();
        }
        final FileOutputStream fos = new FileOutputStream(new File(dir, "redreader_crash_log_" + UUID.randomUUID().toString() + ".txt"));
        final PrintWriter pw = new PrintWriter(fos);
        t.printStackTrace(pw);
        pw.flush();
        pw.close();
    } catch (Throwable t1) {
    }
    androidHandler.uncaughtException(thread, t);
}
Example 90
Project: AndroidRepeaterProject-master  File: DownloadService.java View source code
@Override
protected void onHandleIntent(Intent intent) {
    String rawUrl = intent.getStringExtra("url");
    final String downloadTo = intent.getStringExtra("downloadTo");
    try {
        HttpURLConnection connection = followRedirect(rawUrl);
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            LogUtils.i("download failed: http not ok " + connection.getResponseCode());
            sendBroadcast(new DownloadFailedIntent(rawUrl, downloadTo));
            return;
        }
        int fileLength = connection.getContentLength();
        LogUtils.i("download length: " + fileLength);
        InputStream input = connection.getInputStream();
        try {
            FileOutputStream output = new FileOutputStream(downloadTo);
            try {
                byte buffer[] = new byte[65536];
                long total = 0;
                int count;
                while ((count = input.read(buffer)) != -1) {
                    total += count;
                    if (fileLength > 0) {
                        sendBroadcast(new DownloadingIntent(rawUrl, downloadTo, (int) (total * 100 / fileLength)));
                    }
                    output.write(buffer, 0, count);
                }
            } finally {
                output.close();
            }
        } finally {
            input.close();
        }
        sendBroadcast(new DownloadedIntent(rawUrl, downloadTo));
    } catch (Exception e) {
        LogUtils.e("failed to download", e);
        sendBroadcast(new DownloadFailedIntent(rawUrl, downloadTo));
    }
}
Example 91
Project: ilarkesto-master  File: PdfBuilder.java View source code
public static void main(String[] args) throws Throwable {
    PdfBuilder pdf = new PdfBuilder();
    pdf.paragraph().setHeight(72).text("first");
    pdf.paragraph().setHeight(10).text("second");
    pdf.paragraph().setHeight(1);
    pdf.paragraph().text("--------------------------");
    ATable table = pdf.table(50, 50);
    table.cell().paragraph().text("1 ABC");
    table.cell().setBorder(Color.RED, 0.5f).paragraph().text("2 ABCÜÜ\nABCDEF");
    table.cell().paragraph().text("3 ABC");
    table.cell().paragraph().text("4 ABC");
    pdf.write(new FileOutputStream("c:/tmp/test.pdf"));
}
Example 92
Project: tmdm-studio-se-master  File: JobJavaScriptsManager.java View source code
/**
     * DOC Administrator Comment method "createLauncherFile".
     * 
     * @param process
     * @param list
     * @param cmdPrimary
     * @param cmdSecondary
     * @param tmpFold
     */
private void createLauncherFile(ProcessItem process, List<URL> list, String cmdPrimary, String fileName, String tmpFold) {
    PrintWriter pw = null;
    try {
        //$NON-NLS-1$
        File file = new File(tmpFold, process.getProperty().getLabel() + "_" + fileName);
        file.createNewFile();
        pw = new PrintWriter(new FileOutputStream(file));
        pw.print(cmdPrimary);
        pw.flush();
        list.add(file.toURL());
        pw.close();
    } catch (Exception e) {
        ExceptionHandler.process(e);
    } finally {
        try {
            if (pw != null) {
                pw.close();
            }
        } catch (Exception e) {
        }
    }
}
Example 93
Project: cardslib-master  File: BitmapUtils.java View source code
/**
     * Creates a File from a Bitmap
     *
     * @param bitmap to convert in a file
     *
     * @return File
     */
public static File createFileFromBitmap(Bitmap bitmap) {
    if (bitmap == null)
        return null;
    File photoFile = null;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
    File photoStorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    if (photoStorage != null) {
        photoFile = new File(photoStorage, (System.currentTimeMillis()) + ".png");
        try {
            //f.createNewFile();
            FileOutputStream fo = new FileOutputStream(photoFile);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            Log.e(TAG, "Error saving image ", e);
        }
    }
    return photoFile;
}
Example 94
Project: TestingStuff-master  File: ImageUtil.java View source code
public static boolean getFile(Context context, String url, String path, String fileName) {
    boolean success = false;
    InputStream in = null;
    FileOutputStream fos = null;
    try {
        ImageUtil.log("getFile Bitmap from: " + url);
        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setConnectTimeout(20000);
        c.setReadTimeout(20000);
        c.setRequestMethod("GET");
        c.connect();
        in = c.getInputStream();
        fos = new FileOutputStream(path + fileName);
        int length = 256;
        byte[] buffer = new byte[length];
        int size = in.read(buffer, 0, length);
        while (size != -1) {
            fos.write(buffer, 0, size);
            buffer = new byte[length];
            size = in.read(buffer, 0, length);
        }
        success = true;
    } catch (Exception e) {
        e.printStackTrace();
        ImageUtil.log("Could not load Bitmap from: " + url);
    }
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return success;
}
Example 95
Project: hadoop-on-lustre2-master  File: TestMRCJCRunJar.java View source code
private File makeTestJar() throws IOException {
    File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_NAME);
    JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jarFile));
    InputStream entryInputStream = this.getClass().getResourceAsStream(CLASS_NAME);
    ZipEntry entry = new ZipEntry("org/apache/hadoop/util/" + CLASS_NAME);
    jstream.putNextEntry(entry);
    BufferedInputStream bufInputStream = new BufferedInputStream(entryInputStream, 2048);
    int count;
    byte[] data = new byte[2048];
    while ((count = bufInputStream.read(data, 0, 2048)) != -1) {
        jstream.write(data, 0, count);
    }
    jstream.closeEntry();
    jstream.close();
    return jarFile;
}
Example 96
Project: korsakow-editor-master  File: FontExportTask.java View source code
@Override
public void runTask() throws TaskException {
    if (!fontsToExport.isEmpty()) {
        // this is for the benefit of the flash player
        // which due to a technicality can use only embedded fonts...
        fontsToExport.add(new Font("Arial", Font.PLAIN, 12));
        FontEncoderFactory.getDefaultFactory().addRequiredInputFormat(FontFormat.TTF);
        FontEncoderFactory.getDefaultFactory().addRequiredOutputFormat(FontFormat.SWF);
        destFile.getParentFile().mkdirs();
        try {
            FontEncoder fontEncoder = FontEncoderFactory.getDefaultFactory().createFontEncoder();
            fontEncoder.addAllFonts(fontsToExport);
            fontEncoder.encode(Exporter.FONT_EXPORT_FORMAT, new FileOutputStream(destFile));
        } catch (FontEncoderException e) {
            throw new TaskException(e);
        } catch (FileNotFoundException e) {
            throw new TaskException(e);
        }
    }
}
Example 97
Project: h2-bitmap-master  File: Newsfeed.java View source code
/**
     * This method is called when executing this sample application from the
     * command line.
     *
     * @param args the command line parameters
     */
public static void main(String... args) throws Exception {
    String targetDir = args.length == 0 ? "." : args[0];
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
    InputStream in = Newsfeed.class.getResourceAsStream("newsfeed.sql");
    ResultSet rs = RunScript.execute(conn, new InputStreamReader(in, "ISO-8859-1"));
    in.close();
    while (rs.next()) {
        String file = rs.getString("FILE");
        String content = rs.getString("CONTENT");
        if (file.endsWith(".txt")) {
            content = convertHtml2Text(content);
        }
        new File(targetDir).mkdirs();
        FileOutputStream out = new FileOutputStream(targetDir + "/" + file);
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        writer.write(content);
        writer.close();
        out.close();
    }
    conn.close();
}
Example 98
Project: Yhb-2.0-master  File: DBManager.java View source code
private SQLiteDatabase openDatabase(String dbfile) {
    try {
        Log.e("cc", "open and return");
        file = new File(dbfile);
        if (!file.exists()) {
            Log.e("cc", "file");
            InputStream is = context.getResources().openRawResource(R.raw.city);
            if (is != null) {
                Log.e("cc", "is null");
            } else {
            }
            FileOutputStream fos = new FileOutputStream(dbfile);
            if (is != null) {
                Log.e("cc", "fosnull");
            } else {
            }
            byte[] buffer = new byte[BUFFER_SIZE];
            int count = 0;
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
                Log.e("cc", "while");
                fos.flush();
            }
            fos.close();
            is.close();
        }
        database = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
        return database;
    } catch (FileNotFoundException e) {
        Log.e("cc", "File not found");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("cc", "IO exception");
        e.printStackTrace();
    } catch (Exception e) {
        Log.e("cc", "exception " + e.toString());
    }
    return null;
}
Example 99
Project: arquillian-eclipse-master  File: AbstractArquillianTest.java View source code
public static File createFile(String entryName) throws IOException, FileNotFoundException {
    Bundle bundle = Platform.getBundle(ArquillianTestActivator.PLUGIN_ID);
    URL url = bundle.getEntry("projects/testProject.zip");
    File outputFile = File.createTempFile("tempProject", ".zip");
    InputStream in = null;
    OutputStream out = null;
    try {
        in = url.openStream();
        out = new FileOutputStream(outputFile);
        copy(in, out);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
            }
        }
    }
    return outputFile;
}
Example 100
Project: powermock-master  File: DebuggingClassWriter.java View source code
public Object run() {
    byte[] b = DebuggingClassWriter.super.toByteArray();
    if (debugLocation != null) {
        String dirs = className.replace('.', File.separatorChar);
        try {
            new File(debugLocation + File.separatorChar + dirs).getParentFile().mkdirs();
            File file = new File(new File(debugLocation), dirs + ".class");
            OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            try {
                out.write(b);
            } finally {
                out.close();
            }
            if (traceEnabled) {
                file = new File(new File(debugLocation), dirs + ".asm");
                out = new BufferedOutputStream(new FileOutputStream(file));
                try {
                    ClassReader cr = new ClassReader(b);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
                    TraceClassVisitor tcv = new TraceClassVisitor(null, pw);
                    cr.accept(tcv, 0);
                    pw.flush();
                } finally {
                    out.close();
                }
            }
        } catch (IOException e) {
            throw new CodeGenerationException(e);
        }
    }
    return b;
}
Example 101
Project: BioWiki-master  File: CachedDownloader.java View source code
public void downloadFromUrl(String DownloadUrl, String fileName, String fileType) {
    try {
        File dir = new File(root.getAbsolutePath() + "/" + fileType);
        if (dir.exists() == false) {
            dir.mkdirs();
        }
        //you can write here any link
        URL url = new URL(DownloadUrl);
        File file = new File(dir, fileName);
        long startTime = System.currentTimeMillis();
        Log.d("DownloadManager", "download beginning");
        Log.d("DownloadManager", "download url:" + url);
        Log.d("DownloadManager", "downloaded file name:" + fileName);
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();
        /*
            * Define InputStreams to read from the URLConnection.
            */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        /*
            * Read bytes to the Buffer until there is nothing more to read(-1).
            */
        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
        File UAG = new File(dir, "." + fileName);
        UAG.createNewFile();
        Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
    } catch (IOException e) {
        Log.d("DownloadManager", "Error: " + e);
    }
}