Example usage for java.io BufferedInputStream read

List of usage examples for java.io BufferedInputStream read

Introduction

In this page you can find the example usage for java.io BufferedInputStream read.

Prototype

public synchronized int read(byte b[], int off, int len) throws IOException 

Source Link

Document

Reads bytes from this byte-input stream into the specified byte array, starting at the given offset.

Usage

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.sav.SAVFileReaderSpi.java

@Override
public boolean canDecodeInput(Object source) throws IOException {
    dbgLog.fine("this method is actually called: object");
    if (!(source instanceof BufferedInputStream)) {
        return false;
    } else if (source instanceof File) {
        dbgLog.fine("source is a File object");
    } else {/*ww w. ja va 2s  .c  om*/
        dbgLog.fine("not File object");
    }
    if (source == null) {
        throw new IllegalArgumentException("source == null!");
    }
    BufferedInputStream stream = (BufferedInputStream) source;

    dbgLog.fine("applying the sav test\n");

    byte[] b = new byte[SAV_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }
    int nbytes = stream.read(b, 0, SAV_HEADER_SIZE);

    if (nbytes == 0) {
        throw new IOException();
    }
    //printHexDump(b, "hex dump of the byte-array");
    dbgLog.fine("hex dump of the 1st 4 bytes[$FL2 == 24 46 4C 32]=" + new String(Hex.encodeHex(b)));
    if (stream.markSupported()) {
        stream.reset();
    }

    boolean DEBUG = false;

    String hdr4sav = new String(b);
    dbgLog.fine("from string[$FL2 == 24 46 4C 32]=" + new String(Hex.encodeHex(b)).toUpperCase());

    if (hdr4sav.equals(SAV_FILE_SIGNATURE)) {
        dbgLog.fine("this file is spss-sav type");
        return true;
    } else {
        dbgLog.fine("this file is NOT spss-sav type");
        return false;
    }
}

From source file:JarBuilder.java

/** Adds the file to the given path and name
 *
 * @param file     the file to be added//from w  w  w.j  a v a  2  s .  c o  m
 * @param parent   the directory to the path in which the file is to be added
 * @param fileName the name of the file in the archive
 */
public void addFile(File file, String parent, String fileName) throws IOException {
    byte data[] = new byte[2048];

    FileInputStream fi = new FileInputStream(file.getAbsolutePath());
    BufferedInputStream origin = new BufferedInputStream(fi, 2048);

    JarEntry entry = new JarEntry(makeName(parent, fileName));
    _output.putNextEntry(entry);

    int count = origin.read(data, 0, 2048);
    while (count != -1) {
        _output.write(data, 0, count);
        count = origin.read(data, 0, 2048);
    }

    origin.close();
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReaderSpi.java

@Override
public boolean canDecodeInput(Object source) throws IOException {
    if (!(source instanceof BufferedInputStream)) {
        return false;
    }//from w ww.  j  a  v  a 2 s.c o m
    if (source == null) {
        throw new IllegalArgumentException("stream == null!");
    }
    BufferedInputStream stream = (BufferedInputStream) source;
    dbgLog.fine("applying the dta test\n");

    byte[] b = new byte[DTA_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }
    int nbytes = stream.read(b, 0, DTA_HEADER_SIZE);

    if (nbytes == 0) {
        throw new IOException();
    }

    if (stream.markSupported()) {
        stream.reset();
    }

    dbgLog.info("hex dump: 1st 4bytes =>" + new String(Hex.encodeHex(b)) + "<-");

    if (b[2] != 1) {
        dbgLog.fine("3rd byte is not 1: given file is not stata-dta type");
        return false;
    } else if ((b[1] != 1) && (b[1] != 2)) {
        dbgLog.fine("2nd byte is neither 0 nor 1: this file is not stata-dta type");
        return false;
    } else if (!DTAFileReaderSpi.stataReleaseNumber.containsKey(b[0])) {
        dbgLog.fine("1st byte (" + b[0] + ") is not within the ingestable range [rel. 3-10]:"
                + "this file is NOT stata-dta type");
        return false;
    } else {
        dbgLog.fine("this file is stata-dta type: " + DTAFileReaderSpi.stataReleaseNumber.get(b[0])
                + "(No in byte=" + b[0] + ")");
        return true;
    }
}

From source file:com.phonegap.FileUtils.java

/**
 * Read content of text file and return as base64 encoded data url.
 * //from  w ww  .ja  v a  2s . c  om
 * @param filename         The name of the file.
 * @return               Contents of file = data:<media type>;base64,<data>
 * @throws FileNotFoundException, IOException
 */
public String readAsDataURL(String filename) throws FileNotFoundException, IOException {
    byte[] bytes = new byte[1000];
    BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int numRead = 0;
    while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
        bos.write(bytes, 0, numRead);
    }

    // Determine content type from file name
    String contentType = null;
    if (filename.startsWith("content:")) {
        Uri fileUri = Uri.parse(filename);
        contentType = this.ctx.getContentResolver().getType(fileUri);
    } else {
        MimeTypeMap map = MimeTypeMap.getSingleton();
        contentType = map.getMimeTypeFromExtension(map.getFileExtensionFromUrl(filename));
    }

    byte[] base64 = Base64.encodeBase64(bos.toByteArray());
    String data = "data:" + contentType + ";base64," + new String(base64);
    return data;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.dta.DTAFileReaderSpi.java

@Override
public boolean canDecodeInput(Object source) throws IOException {
    if (!(source instanceof BufferedInputStream)) {
        return false;
    }/*from   w  w  w . ja v  a  2s  .co  m*/
    if (source == null) {
        throw new IllegalArgumentException("stream == null!");
    }
    BufferedInputStream stream = (BufferedInputStream) source;
    dbgLog.fine("applying the dta test\n");

    byte[] b = new byte[DTA_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }
    int nbytes = stream.read(b, 0, DTA_HEADER_SIZE);

    if (nbytes == 0) {
        throw new IOException();
    }
    //printHexDump(b, "hex dump of the byte-array");

    if (stream.markSupported()) {
        stream.reset();
    }

    dbgLog.info("hex dump: 1st 4bytes =>" + new String(Hex.encodeHex(b)) + "<-");

    if (b[2] != 1) {
        dbgLog.fine("3rd byte is not 1: given file is not stata-dta type");
        return false;
    } else if ((b[1] != 1) && (b[1] != 2)) {
        dbgLog.fine("2nd byte is neither 0 nor 1: this file is not stata-dta type");
        return false;
    } else if (!DTAFileReaderSpi.stataReleaseNumber.containsKey(b[0])) {
        dbgLog.fine("1st byte (" + b[0] + ") is not within the ingestable range [rel. 3-10]:"
                + "this file is NOT stata-dta type");
        return false;
    } else {
        dbgLog.fine("this file is stata-dta type: " + DTAFileReaderSpi.stataReleaseNumber.get(b[0])
                + "(No in byte=" + b[0] + ")");
        return true;
    }
}

From source file:com.flagleader.builder.BuilderConfig.java

public static void jarExtracting(String paramString1, String paramString2) {
    int i1 = 2048;
    BufferedOutputStream localBufferedOutputStream = null;
    BufferedInputStream localBufferedInputStream = null;
    JarEntry localJarEntry = null;
    JarFile localJarFile = null;// w  w  w  . jav  a  2s.  c o m
    Enumeration localEnumeration = null;
    try {
        localJarFile = new JarFile(paramString2);
        localEnumeration = localJarFile.entries();
        while (localEnumeration.hasMoreElements()) {
            localJarEntry = (JarEntry) localEnumeration.nextElement();
            if (localJarEntry.isDirectory()) {
                new File(paramString1 + localJarEntry.getName()).mkdirs();
            } else {
                localBufferedInputStream = new BufferedInputStream(localJarFile.getInputStream(localJarEntry));
                byte[] arrayOfByte = new byte[i1];
                FileOutputStream localFileOutputStream = new FileOutputStream(
                        paramString1 + localJarEntry.getName());
                localBufferedOutputStream = new BufferedOutputStream(localFileOutputStream, i1);
                int i2;
                while ((i2 = localBufferedInputStream.read(arrayOfByte, 0, i1)) != -1)
                    localBufferedOutputStream.write(arrayOfByte, 0, i2);
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
                localBufferedInputStream.close();
            }
        }
    } catch (Exception localException1) {
        localException1.printStackTrace();
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException2) {
            localException2.printStackTrace();
        }
    } finally {
        try {
            if (localBufferedOutputStream != null) {
                localBufferedOutputStream.flush();
                localBufferedOutputStream.close();
            }
            if (localBufferedInputStream != null)
                localBufferedInputStream.close();
        } catch (Exception localException3) {
            localException3.printStackTrace();
        }
    }
}

From source file:com.oneops.cms.crypto.CmsCryptoDES.java

private KeyParameter getSecretKeyFromFile() throws IOException, GeneralSecurityException {
    BufferedInputStream keystream = new BufferedInputStream(new FileInputStream(secretKeyFile));
    int len = keystream.available();
    if (len < MIN_DES_FILE_LENGTH) {
        keystream.close();/* w w w.  j  a v a  2 s.  c o m*/
        throw new EOFException(">>>> Bad DES file length = " + len);
    }
    byte[] keyhex = new byte[len];
    keystream.read(keyhex, 0, len);
    keystream.close();
    return new KeyParameter(Hex.decode(keyhex));
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private void doDownloadUrlToFile(URL downloadURL, File downloadFile) throws Exception {
    HttpClient client = createHttpClient(downloadURL);
    HttpMethod getRequest = new GetMethod(downloadURL.toString());
    try {//from  w w w.j av  a2 s  .c om
        int status = -1;
        for (int attempts = 0; attempts < MAX_ATTEMPTS && status != HTTP_SUCCESS_CODE; attempts++)
            status = client.executeMethod(getRequest);
        if (status != HTTP_SUCCESS_CODE)
            throw new Exception("Got " + status + " status trying to download file " + downloadURL.toString()
                    + " to " + downloadFile.toString());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(downloadFile));
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            out.write(block, 0, bytes);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        throw e;
    } finally {
        getRequest.releaseConnection();
    }
}

From source file:com.dimdim.conference.application.portal.PortalServerAdapter.java

/**
 * @param url//  ww  w .jav  a 2s .co  m
 * @param arguments
 * @return
 */
protected synchronized String getURL_String(HttpClient client, String url) {
    GetMethod method = null;
    String responseBody = null;
    try {

        System.out.println("Getting URL:" + url);
        //         System.out.println("Posting data:"+args);
        method = new GetMethod(url);
        //        method.setRequestBody(args);
        method.setFollowRedirects(true);

        //execute the method
        client.setTimeout(2000);
        System.out.println("Calling url:" + url);
        StringBuffer buf = new StringBuffer();
        client.executeMethod(method);
        InputStream is = method.getResponseBodyAsStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] ary = new byte[256];
        int len = 0;
        while ((len = bis.read(ary, 0, 256)) > 0) {
            String str = new String(ary, 0, len);
            //               System.out.println("Received buffer:"+str);
            buf.append(str);
        }
        try {
            bis.close();
            is.close();
        } catch (Exception e) {
        }
        responseBody = buf.toString();
        System.out.println("Called ----:" + url);
    } catch (HttpException he) {
        he.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    //clean up the connection resources
    try {
        method.releaseConnection();
    } catch (Exception ee) {
        //   Ignore the exceptions in cleanup.
    }
    return responseBody;
}

From source file:com.eurotong.orderhelperandroid.Common.java

@TargetApi(9)
public static void downloadFile(String fileName) {
    try {//from w  w  w  .ja va2s.  c o m
        //http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        Date date = new Date();
        String datetime = dateFormat.format(date);
        // Create a URL for the desired page          
        URL url = new URL(
                Common.GetBaseUrl() + Customer.Current().CustomerID + "/" + fileName + "?d=" + datetime);

        // Read all the text returned by the server  

        BufferedInputStream in = new BufferedInputStream(url.openStream());

        //http://stackoverflow.com/questions/4228699/write-and-read-strings-to-from-internal-file
        FileOutputStream fos = MyApplication.getAppContext().openFileOutput(fileName, Context.MODE_PRIVATE);
        /*
        DataOutputStream out = 
            new DataOutputStream(fos);
                
        String str;
        while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
           Log.i(Define.APP_CATALOG, str);
           out.writeUTF(str);
        }
        */
        BufferedOutputStream out = new BufferedOutputStream(fos, 4096);
        byte[] data = new byte[4096];
        int bytesRead = 0, totalRead = 0;
        while ((bytesRead = in.read(data, 0, data.length)) >= 0) {
            out.write(data, 0, bytesRead);

            // update progress bar
            totalRead += bytesRead;
            /*
            int totalReadInKB = totalRead / 1024;
            msg = Message.obtain(parentActivity.activityHandler,
                            AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR,
                            totalReadInKB, 0);
            parentActivity.activityHandler.sendMessage(msg);
            */
        }

        in.close();
        //fos.close();
        out.close();

        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_file_finished),
                Toast.LENGTH_LONG).show();

        try {
            if (fileName.equals(Define.MENU_FILE_NAME)) {
                Product.ParseMenuList(Common.GetFileInputStreamFromStorage(fileName));
                Log.i(Define.APP_CATALOG, "menus size:" + "");
                Product.Reload();
            } else if (fileName.equals(Define.PRINT_LAYOUT_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_NAME);
                PrintLayout.Reload();
            } else if (fileName.equals(Define.BUSINESS_INFO_FILE_NAME)) {
                BusinessInfo bi = BusinessInfo
                        .Parse(Common.GetFileInputStreamFromStorage(Define.BUSINESS_INFO_FILE_NAME));
                Log.i(Define.APP_CATALOG, "setting: businessname:" + bi.getBusinessName());
                BusinessInfo.Reload();
            } else if (fileName.equals(Define.SETTING_FILE_NAME)) {
                Setting setting = Setting.Parse(Common.GetFileInputStreamFromStorage(Define.SETTING_FILE_NAME));
                Log.i(Define.APP_CATALOG, "setting: printer port" + setting.getPrinterPort());
                setting.Reload();
            } else if (fileName.equals(Define.PRINT_LAYOUT_BAR_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_BAR_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_BAR_NAME);
                PrintLayout.Reload();
            }

            else if (fileName.equals(Define.PRINT_LAYOUT_KITCHEN_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_KITCHEN_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_KITCHEN_NAME);
                PrintLayout.Reload();
            } else if (fileName.equals(Define.DEVICE_FILE)) {
                Device bi = Device.Parse(Common.GetFileInputStreamFromStorage(Define.DEVICE_FILE));
                Log.i(Define.APP_CATALOG, Define.DEVICE_FILE);
                Device.Reload();
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        Log.e(Define.APP_CATALOG, e.toString());
    } catch (IOException e) {
        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_error),
                Toast.LENGTH_LONG).show();
        Log.e(Define.APP_CATALOG, e.toString());
        e.printStackTrace();
    } catch (Exception e) {
        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_error),
                Toast.LENGTH_LONG).show();
        Log.e(Define.APP_CATALOG, e.toString());
    }
}