Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

In this page you can find the example usage for java.io BufferedOutputStream write.

Prototype

@Override
public synchronized void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Usage

From source file:com.buaa.cfs.utils.FileUtil.java

private static void unpackEntries(TarArchiveInputStream tis, TarArchiveEntry entry, File outputDir)
        throws IOException {
    if (entry.isDirectory()) {
        File subDir = new File(outputDir, entry.getName());
        if (!subDir.mkdirs() && !subDir.isDirectory()) {
            throw new IOException("Mkdirs failed to create tar internal dir " + outputDir);
        }//from  w  ww  . j a  v a 2  s  .c  o m

        for (TarArchiveEntry e : entry.getDirectoryEntries()) {
            unpackEntries(tis, e, subDir);
        }

        return;
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        if (!outputFile.getParentFile().mkdirs()) {
            throw new IOException("Mkdirs failed to create tar internal dir " + outputDir);
        }
    }

    int count;
    byte data[] = new byte[2048];
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    while ((count = tis.read(data)) != -1) {
        outputStream.write(data, 0, count);
    }

    outputStream.flush();
    outputStream.close();
}

From source file:com.parasoft.em.client.impl.JSONClient.java

protected JSONObject doPost(String restPath, JSONObject payload) throws IOException {
    HttpURLConnection connection = getConnection(restPath);
    connection.setRequestMethod("POST");
    if (payload != null) {
        String payloadString = payload.toString();
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        BufferedOutputStream stream = new BufferedOutputStream(connection.getOutputStream());
        try {/*from   www .  j ava2s . c om*/
            byte[] bytes = payloadString.getBytes("UTF-8");
            stream.write(bytes, 0, bytes.length);
        } finally {
            stream.close();
        }
    }
    int responseCode = connection.getResponseCode();
    if (responseCode / 100 == 2) {
        return getResponseJSON(connection.getInputStream());
    } else {
        String errorMessage = getResponseString(connection.getErrorStream());
        throw new IOException(restPath + ' ' + responseCode + '\n' + errorMessage);
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public void activate(final Context context, final SignedObj obj) {
    Runnable r = new Runnable() {
        @Override//  w w w  . j  a v  a2 s .c  o  m
        public void run() {
            byte[] bytes = obj.getRaw();
            if (bytes == null) {
                Pair<JSONObject, byte[]> p = splitRaw(obj.getJson());
                //                content = p.first;
                bytes = p.second;
            }

            /*AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bytes.length, AudioTrack.MODE_STATIC);
            track.write(bytes, 0, bytes.length);
            try { // TODO: hack.
            Thread.sleep(500);
             } catch (InterruptedException e) {
             }
            track.play();
            */
            /****/

            File file = new File(getTempFilename());
            try {
                OutputStream os = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                bos.write(bytes, 0, bytes.length);
                bos.flush();
                bos.close();

                copyWaveFile(getTempFilename(), getFilename());
                deleteTempFile();

                MediaPlayer mp = new MediaPlayer();

                mp.setDataSource(getFilename());
                mp.prepare();
                mp.start();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    if (context instanceof Activity) {
        ((Activity) context).runOnUiThread(r);
    } else {
        r.run();
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.obj.action.PlayAllAudioAction.java

public void playNextSong() {
    if (c.isAfterLast()) {
        c.close();/*from w w  w . jav a  2s.  c  om*/
        alert.dismiss();
        return;
    }

    try {
        final JSONObject objData = new JSONObject(c.getString(c.getColumnIndex(DbObject.JSON)));
        Runnable r = new Runnable() {
            @Override
            public void run() {

                Log.w("PlayAllAudioAction", objData.optString("feedName"));
                byte bytes[] = Base64.decode(objData.optString(VoiceObj.DATA), Base64.DEFAULT);

                File file = new File(getTempFilename());
                try {
                    OutputStream os = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(os);
                    bos.write(bytes, 0, bytes.length);
                    bos.flush();
                    bos.close();

                    copyWaveFile(getTempFilename(), getFilename());
                    deleteTempFile();

                    mp = new MediaPlayer();

                    mp.setDataSource(getFilename());
                    mp.setOnCompletionListener(new OnCompletionListener() {

                        public void onCompletion(MediaPlayer m) {
                            Log.w("PlayAllAudioAction", "finished");
                            c.moveToNext();
                            playNextSong();
                        }
                    });
                    mp.prepare();
                    mp.start();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        if (context instanceof Activity) {
            ((Activity) context).runOnUiThread(r);
        } else {
            r.run();
        }
    } catch (Exception e) {
    }

}

From source file:com.android.tradefed.util.FileUtil.java

public static void extractGzip(File tarGzipFile, File destDir, String destName)
        throws FileNotFoundException, IOException, ArchiveException {
    GZIPInputStream zipIn = null;
    BufferedOutputStream buffOut = null;
    try {/*www.ja  va2  s . com*/
        File destUnzipFile = new File(destDir.getAbsolutePath(), destName);
        zipIn = new GZIPInputStream(new FileInputStream(tarGzipFile));
        buffOut = new BufferedOutputStream(new FileOutputStream(destUnzipFile));
        int b = 0;
        byte[] buf = new byte[8192];
        while ((b = zipIn.read(buf)) != -1) {
            buffOut.write(buf, 0, b);
        }
    } finally {
        if (zipIn != null)
            zipIn.close();
        if (buffOut != null)
            buffOut.close();
    }
}

From source file:edu.wustl.xipHost.caGrid.RetrieveNBIASecuredTest.java

@Test
public void test() throws Exception {
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    Login login = new GridLogin();
    String userName = "<JIRAusername>";
    String password = "<JIRApassword>";
    DcmFileFilter dcmFilter = new DcmFileFilter();
    login.login(userName, password);//from   www. ja v  a  2 s .co m
    GlobusCredential globusCred = login.getGlobusCredential();
    boolean isConnectionSecured = login.isConnectionSecured();
    logger.debug("Acquired NBIA GlobusCredential. Connection secured = " + isConnectionSecured);
    if (!isConnectionSecured) {
        fail("Unable to acquire NBIA GlobusCredential. Check username and password.");
        return;
    }
    NCIACoreServiceClient client = new NCIACoreServiceClient(gridServiceUrl, globusCred);
    client.setAnonymousPrefered(false);
    TransferServiceContextReference tscr = client.retrieveDicomDataBySeriesUID("1.3.6.1.4.1.9328.50.1.4718");
    TransferServiceContextClient tclient = new TransferServiceContextClient(tscr.getEndpointReference(),
            globusCred);
    InputStream istream = TransferClientHelper.getData(tclient.getDataTransferDescriptor(), globusCred);
    ZipInputStream zis = new ZipInputStream(istream);
    ZipEntryInputStream zeis = null;
    BufferedInputStream bis = null;
    File importDir = new File("./test-content/NBIA5");
    if (!importDir.exists()) {
        importDir.mkdirs();
    } else {
        File[] files = importDir.listFiles(dcmFilter);
        for (int j = 0; j < files.length; j++) {
            File file = files[j];
            file.delete();
        }
    }
    while (true) {
        try {
            zeis = new ZipEntryInputStream(zis);
        } catch (EOFException e) {
            break;
        } catch (IOException e) {
            logger.error(e, e);
        }
        String unzzipedFile = null;
        try {
            unzzipedFile = importDir.getCanonicalPath();
        } catch (IOException e) {
            logger.error(e, e);
        }
        logger.debug(" filename: " + zeis.getName());
        bis = new BufferedInputStream(zeis);
        byte[] data = new byte[8192];
        int bytesRead = 0;
        String retrievedFilePath = unzzipedFile + File.separator + zeis.getName();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(retrievedFilePath));
            while ((bytesRead = (bis.read(data, 0, data.length))) != -1) {
                bos.write(data, 0, bytesRead);
            }
            bos.flush();
            bos.close();
        } catch (IOException e) {
            logger.error(e, e);
        }
    }
    try {
        zis.close();
        tclient.destroy();
    } catch (IOException e) {
        logger.error(e, e);
    }
    File[] retrievedFiles = importDir.listFiles(dcmFilter);
    int numbOfRetreivedFiles = retrievedFiles.length;
    assertEquals("Number of retrieved files should be 2 but is. " + numbOfRetreivedFiles, numbOfRetreivedFiles,
            2);
    //Assert file names. They should be equal to items' SeriesInstanceUIDs
    Map<String, File> mapRetrievedFiles = new HashMap<String, File>();
    for (int i = 0; i < numbOfRetreivedFiles; i++) {
        File file = retrievedFiles[i];
        mapRetrievedFiles.put(file.getName(), file);
    }
    boolean retrievedFilesCorrect = false;
    if (mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4716.dcm")
            && mapRetrievedFiles.containsKey("1.3.6.1.4.1.9328.50.1.4720.dcm")) {
        retrievedFilesCorrect = true;
    }
    assertTrue("Retrieved files are not as expected.", retrievedFilesCorrect);
}

From source file:eu.scape_project.hawarp.webarchive.PayloadContent.java

private byte[] inputStreamToByteArray() {
    try {//from w  w w .  j  a  v a  2s .  co m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedInputStream buffis = new BufferedInputStream(inputStream);
        BufferedOutputStream buffos = new BufferedOutputStream(baos);
        byte[] tempBuffer = new byte[8192];
        int bytesRead;
        boolean firstByteArray = true;
        while ((bytesRead = buffis.read(tempBuffer)) != -1) {
            buffos.write(tempBuffer, 0, bytesRead);
            if (doPayloadIdentification && firstByteArray && tempBuffer != null && bytesRead > 0) {
                identified = identifyPayloadType(tempBuffer);
            }
            firstByteArray = false;
        }
        //buffis.close();
        buffos.flush();
        buffos.close();

        return baos.toByteArray();
    } catch (IOException ex) {
        LOG.error("Error while trying to read payload content", ex);
        this.error = true;
        return null;
    }
}

From source file:mobisocial.nfcserver.handler.HttpFileHandler.java

public int handleNdef(NdefMessage[] ndefMessages) {
    URI page = null;/*from   w ww.  jav  a2 s.  c o  m*/
    NdefRecord firstRecord = ndefMessages[0].getRecords()[0];
    if (UriRecord.isUri(firstRecord)) {
        page = UriRecord.parse(firstRecord).getUri();
    }

    try {
        if (page != null && (page.getScheme().startsWith("http"))) {
            System.out.println("trying to get " + page);
            if (page.getPath() == null || !page.toString().contains(".")) {
                return NDEF_PROPAGATE;
            }

            try {
                String extension = page.toString().substring(page.toString().lastIndexOf(".") + 1);
                if (!MimeTypeHandler.MIME_EXTENSIONS.containsValue(extension)) {
                    return NDEF_PROPAGATE;
                }

                // Download content
                System.out.println("Downloading " + extension + " file.");
                HttpGet httpGet = new HttpGet(page);
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity entity = httpResponse.getEntity();
                InputStream content = entity.getContent();

                File fileOut = new File("nfcfiles/" + System.currentTimeMillis() + "." + extension);
                fileOut.getParentFile().mkdirs();
                FileOutputStream fileOutStream = new FileOutputStream(fileOut);
                BufferedOutputStream buffered = new BufferedOutputStream(fileOutStream);
                byte[] buf = new byte[1024];
                while (true) {
                    int r = content.read(buf);
                    if (r <= 0)
                        break;
                    buffered.write(buf, 0, r);
                }
                buffered.close();
                fileOutStream.close();

                MimeTypeHandler.openFile(fileOut);
                return NDEF_CONSUME;
            } catch (Exception e) {
                e.printStackTrace();
                return NDEF_PROPAGATE;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error launching page", e);
    }
    return NDEF_PROPAGATE;
}

From source file:com.wavemaker.StudioInstallService.java

public static File unzipFile(File zipfile) {
    int BUFFER = 2048;

    String zipname = zipfile.getName();
    int extindex = zipname.lastIndexOf(".");

    try {/*  w ww  .  jav  a  2s .  c o  m*/
        File zipFolder = new File(zipfile.getParentFile(), zipname.substring(0, extindex));
        if (zipFolder.exists())
            org.apache.commons.io.FileUtils.deleteDirectory(zipFolder);
        zipFolder.mkdir();

        File currentDir = zipFolder;
        //File currentDir = zipfile.getParentFile();

        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream(zipfile.toString());
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                File f = new File(currentDir, entry.getName());
                if (f.exists())
                    f.delete(); // relevant if this is the top level folder
                f.mkdir();
            } else {
                int count;
                byte data[] = new byte[BUFFER];
                //needed for non-dir file ace/ace.js created by 7zip
                File destFile = new File(currentDir, entry.getName());
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(currentDir.toString() + "/" + entry.getName());
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
        zis.close();

        return currentDir;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (File) null;

}

From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpResponseModel responseModel = new HttpResponseModel();
    try {/*from   w  w w  .  j  a  v  a  2 s  . co  m*/
        boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ???
        if (isMultipart) {
            Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ??
            List<String> fileList = new ArrayList<String>();// 

            // DiskFileItemFactory??
            // ????List
            // list???
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();
                if (item.isFormField()) {
                    // ?
                    String sFieldName = item.getFieldName();
                    String sFieldValue = item.getString("UTF-8");
                    htSubmitParam.put(sFieldName, sFieldValue);
                } else {
                    // ,???
                    String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString()
                            + ".jpg";
                    File filePath = new File(
                            getServletConfig().getServletContext().getRealPath(Constants.File_Upload));
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    File file = new File(filePath, newFileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //?
                    BufferedInputStream bis = new BufferedInputStream(item.getInputStream());
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] b = new byte[1024];
                    int length = 0;
                    while ((length = bis.read(b)) > 0) {
                        bos.write(b, 0, length);
                    }
                    bos.close();
                    bis.close();
                    //?url
                    String fileUrl = request.getRequestURL().toString();
                    fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL
                    fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName;
                    /**/
                    fileList.add(fileUrl);
                }
            }

            //
            String unlockInfoId = htSubmitParam.get("UnlockInfoId");
            String imgType = htSubmitParam.get("ImgType");
            String newFileUrl = fileList.get(0);

            UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService");
            UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId));
            if (imgType.equals("customerIdImg")) {
                unlockInfo.setCustomerIdImg(newFileUrl);
            } else if (imgType.equals("customerDrivingLicenseImg")) {
                unlockInfo.setCustomerDrivingLicenseImg(newFileUrl);
            } else if (imgType.equals("customerVehicleLicenseImg")) {
                unlockInfo.setCustomerVehicleLicenseImg(newFileUrl);
            } else if (imgType.equals("customerBusinessLicenseImg")) {
                unlockInfo.setCustomerBusinessLicenseImg(newFileUrl);
            } else if (imgType.equals("customerIntroductionLetterImg")) {
                unlockInfo.setCustomerIntroductionLetterImg(newFileUrl);
            } else if (imgType.equals("unlockWorkOrderImg")) {
                unlockInfo.setUnlockWorkOrderImg(newFileUrl);
            }
            /**/
            unlockInfoService.update(unlockInfo);
        }
    } catch (Exception e) {
        e.printStackTrace();
        responseModel.responseCode = "0";
        responseModel.responseMessage = e.toString();
    }
    /* ??? */
    response.setHeader("content-type", "text/json;charset=utf-8");
    response.getOutputStream().write(responseModel.toByteArray());
}