Example usage for java.io ByteArrayInputStream read

List of usage examples for java.io ByteArrayInputStream read

Introduction

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

Prototype

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

Source Link

Document

Reads up to len bytes of data into an array of bytes from this input stream.

Usage

From source file:com.gs.tools.doc.extractor.core.html.HTMLDocumentExtractor.java

private void writeTo(byte[] data, OutputStream outputStream) throws IOException {
    try {// ww  w .j a va  2s .  co m
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        byte[] buffer = new byte[1024 * 1024];
        int count = 0;
        while ((count = bais.read(buffer, 0, 1024 * 1024)) > 0) {
            outputStream.write(buffer, 0, count);
        }
        bais.close();
    } finally {
        outputStream.close();
    }

}

From source file:com.phonegap.FileUtils.java

/**
 * Write contents of file.//from  ww w.  j  av a 2s  . c o m
 * 
 * @param filename         The name of the file.
 * @param data            The contents of the file.
 * @param append         T=append, F=overwrite
 * @throws FileNotFoundException, IOException
 */
public void writeAsText(String filename, String data, boolean append)
        throws FileNotFoundException, IOException {
    String FilePath = filename;
    byte[] rawData = data.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);
    FileOutputStream out = new FileOutputStream(FilePath, append);
    byte buff[] = new byte[rawData.length];
    in.read(buff, 0, buff.length);
    out.write(buff, 0, rawData.length);
    out.flush();
    out.close();
}

From source file:org.lockss.util.TestCharsetUtil.java

/**
 * Method: joinStreamsWithCharset(byte[] buf,
 *                                InputStream tail, String charset)
 *///  w w  w.  j  a v  a 2  s.c  o  m
public void testJoinStreamsWithCharset() throws Exception {
    byte[] buf = new byte[100]; // create an input stream
    String buf_string;
    ByteArrayInputStream bais = new ByteArrayInputStream(HTML_FILE.getBytes("UTF-8"));
    // read the first 100 bytes.
    int in_length = bais.available();
    bais.read(buf, 0, buf.length);
    buf_string = new String(buf, "UTF-8");
    int str_length = buf_string.length();
    assertEquals(in_length - buf.length, bais.available());
    // create a new CharsetReader
    Reader rdr = CharsetUtil.joinStreamsWithCharset(buf, bais, "UTF-8");
    char[] charbuf = new char[str_length];
    // read in the chars that we already read...
    rdr.read(charbuf);
    assertEquals(buf_string.toCharArray(), charbuf);
}

From source file:com.chenshu.compress.CompressOldTest.java

@Benchmark
public int jdkGzip2Compress() {
    ByteArrayInputStream bin = null;
    ByteArrayOutputStream bout = null;
    GZIPOutputStream gzout = null;
    try {//from  w  w  w.  j a v  a 2s  .com
        bin = new ByteArrayInputStream(data);
        bout = new ByteArrayOutputStream(data.length);
        gzout = new GZIPOutputStream(bout) {
            {
                def.setLevel(level);
            }
        };
        int count;
        byte ret[] = new byte[1024];
        while ((count = bin.read(ret, 0, 1024)) != -1) {
            gzout.write(ret, 0, count);
        }
        gzout.finish();
        gzout.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (gzout != null) {
            try {
                gzout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bout != null) {
            try {
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    byte[] bs = bout.toByteArray();
    return bs.length;
}

From source file:es.jamisoft.comun.utils.compression.Jar.java

private void metaInf() {
    byte[] buf = "Manifest-Version: 1.0\r\nX-COMMENT: www.jamisoft.es - Jose Antonio Jamilena Daza".getBytes();
    ByteArrayInputStream manifest = new ByteArrayInputStream(buf);
    String asDir = "/META-INF/";
    try {/*from w  ww  .ja  v a  2s .c o  m*/
        String lsRutaAbs = "/META-INF/manifest.mf";
        //String lsRutaRelat = lsRutaAbs.substring(isDirectorioRelativoComp.length(), lsRutaAbs.length());
        String lsRutaRelat = lsRutaAbs;
        JarArchiveEntry entry = new JarArchiveEntry(lsRutaRelat);

        sout.putArchiveEntry(entry);

        byte buffer[] = new byte[2048];
        int liLeido = -1;
        int numCaracteresLeidos = 0;

        while ((liLeido = manifest.read(buffer, 0, 2048)) != -1) {
            sout.write(buffer, 0, liLeido);
        }

        sout.flush();
        sout.closeArchiveEntry();
        manifest.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cyberway.issue.io.arc.ARCRecord.java

/**
* Read http header if present. Technique borrowed from HttpClient HttpParse
* class.//w w  w .  j  a  v a2 s  . co  m
* 
* @return ByteArrayInputStream with the http header in it or null if no
*         http header.
* @throws IOException
*/
private InputStream readHttpHeader() throws IOException {
    // If judged a record that doesn't have an http header, return
    // immediately.
    if (!getHeader().getUrl().startsWith("http") || getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) {
        return null;
    }
    byte[] statusBytes = HttpParser.readRawLine(getIn());
    int eolCharCount = getEolCharsCount(statusBytes);
    if (eolCharCount <= 0) {
        throw new IOException("Failed to read http status where one was expected: "
                + ((statusBytes == null) ? "" : new String(statusBytes)));
    }
    String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount,
            ARCConstants.DEFAULT_ENCODING);
    if ((statusLine == null) || !StatusLine.startsWithHTTP(statusLine)) {
        if (statusLine.startsWith("DELETED")) {
            // Some old ARCs have deleted records like following:
            // http://vireo.gatech.edu:80/ebt-bin/nph-dweb/dynaweb/SGI_Developer/SGITCL_PG/@Generic__BookTocView/11108%3Btd%3D2 130.207.168.42 19991010131803 text/html 29202
            // DELETED_TIME=20000425001133_DELETER=Kurt_REASON=alexalist
            // (follows ~29K spaces)
            // For now, throw a RecoverableIOException so if iterating over
            // records, we keep going.  TODO: Later make a legitimate
            // ARCRecord from the deleted record rather than throw
            // exception.
            throw new DeletedARCRecordIOException(statusLine);
        } else {
            throw new IOException("Failed parse of http status line.");
        }
    }
    this.httpStatus = new StatusLine(statusLine);

    // Save off all bytes read.  Keep them as bytes rather than
    // convert to strings so we don't have to worry about encodings
    // though this should never be a problem doing http headers since
    // its all supposed to be ascii.
    ByteArrayOutputStream baos = new ByteArrayOutputStream(statusBytes.length + 4 * 1024);
    baos.write(statusBytes);

    // Now read rest of the header lines looking for the separation
    // between header and body.
    for (byte[] lineBytes = null; true;) {
        lineBytes = HttpParser.readRawLine(getIn());
        eolCharCount = getEolCharsCount(lineBytes);
        if (eolCharCount <= 0) {
            throw new IOException(
                    "Failed reading http headers: " + ((lineBytes != null) ? new String(lineBytes) : null));
        }
        // Save the bytes read.
        baos.write(lineBytes);
        if ((lineBytes.length - eolCharCount) <= 0) {
            // We've finished reading the http header.
            break;
        }
    }

    byte[] headerBytes = baos.toByteArray();
    // Save off where body starts.
    this.getMetaData().setContentBegin(headerBytes.length);
    ByteArrayInputStream bais = new ByteArrayInputStream(headerBytes);
    if (!bais.markSupported()) {
        throw new IOException("ByteArrayInputStream does not support mark");
    }
    bais.mark(headerBytes.length);
    // Read the status line.  Don't let it into the parseHeaders function.
    // It doesn't know what to do with it.
    bais.read(statusBytes, 0, statusBytes.length);
    this.httpHeaders = HttpParser.parseHeaders(bais, ARCConstants.DEFAULT_ENCODING);
    this.getMetaData().setStatusCode(Integer.toString(getStatusCode()));
    bais.reset();
    return bais;
}

From source file:org.wso2.carbon.analytics.datasource.core.AnalyticsFileSystemTest.java

private void fileReadSeekPosition(String path, int n, int chunk, int... locs) throws IOException {
    byte[] data = generateData(n);
    OutputStream out = this.analyticsFileSystem.createOutput(path);
    out.write(data, 0, data.length);//from  w w  w  . j a v a2  s .  c  o  m
    out.close();
    byte[] din = new byte[chunk];
    ByteArrayInputStream bin = new ByteArrayInputStream(data);
    byte[] din2 = new byte[chunk];
    DataInput in = this.analyticsFileSystem.createInput(path);
    int count, count2;
    for (int i : locs) {
        in.seek(i);
        Assert.assertEquals(in.getPosition(), i);
        count = in.read(din, 0, din.length);
        Assert.assertEquals(in.getPosition(), i + (count < 0 ? 0 : count));
        bin.reset();
        bin.skip(i);
        count2 = bin.read(din2, 0, din2.length);
        Assert.assertEquals(count, count2);
        Assert.assertEquals(din, din2);
    }
}

From source file:com.lmco.ddf.endpoints.rest.TestRestEndpoint.java

/**
 * Converts a ByteArrayInputStream into a readable/printable String
 * @param content//  ww w. j ava2s  .  c o  m
 * @return
 */
protected String byteArrayConvert(ByteArrayInputStream content) {
    int streamSize = content.available();
    char[] charArray = new char[streamSize];
    byte[] byteArray = new byte[streamSize];

    content.read(byteArray, 0, streamSize);
    for (int i = 0; i < streamSize;) {
        charArray[i] = (char) (byteArray[i++] & 0xff);
    }

    return new String(charArray);
}

From source file:org.archive.io.HeaderedArchiveRecord.java

/**
 * Read header if present. Technique borrowed from HttpClient HttpParse
 * class. Using http parser code for now. Later move to more generic header
 * parsing code if there proves a need.//w  w w .  j av  a2  s  . com
 * 
 * @return ByteArrayInputStream with the http header in it or null if no
 *         http header.
 * @throws IOException
 */
private InputStream readContentHeaders() throws IOException {
    // If judged a record that doesn't have an http header, return
    // immediately.
    if (!hasContentHeaders()) {
        return null;
    }
    byte[] statusBytes = LaxHttpParser.readRawLine(getIn());
    int eolCharCount = getEolCharsCount(statusBytes);
    if (eolCharCount <= 0) {
        throw new IOException(
                "Failed to read raw lie where one " + " was expected: " + new String(statusBytes));
    }
    String statusLine = EncodingUtil.getString(statusBytes, 0, statusBytes.length - eolCharCount,
            ARCConstants.DEFAULT_ENCODING);
    if (statusLine == null) {
        throw new NullPointerException("Expected status line is null");
    }
    // TODO: Tighten up this test.
    boolean isHttpResponse = StatusLine.startsWithHTTP(statusLine);
    boolean isHttpRequest = false;
    if (!isHttpResponse) {
        isHttpRequest = statusLine.toUpperCase().startsWith("GET")
                || !statusLine.toUpperCase().startsWith("POST");
    }
    if (!isHttpResponse && !isHttpRequest) {
        throw new UnexpectedStartLineIOException("Failed parse of " + "status line: " + statusLine);
    }
    this.statusCode = isHttpResponse ? (new StatusLine(statusLine)).getStatusCode() : -1;

    // Save off all bytes read.  Keep them as bytes rather than
    // convert to strings so we don't have to worry about encodings
    // though this should never be a problem doing http headers since
    // its all supposed to be ascii.
    ByteArrayOutputStream baos = new ByteArrayOutputStream(statusBytes.length + 4 * 1024);
    baos.write(statusBytes);

    // Now read rest of the header lines looking for the separation
    // between header and body.
    for (byte[] lineBytes = null; true;) {
        lineBytes = LaxHttpParser.readRawLine(getIn());
        eolCharCount = getEolCharsCount(lineBytes);
        if (eolCharCount <= 0) {
            throw new IOException(
                    "Failed reading headers: " + ((lineBytes != null) ? new String(lineBytes) : null));
        }
        // Save the bytes read.
        baos.write(lineBytes);
        if ((lineBytes.length - eolCharCount) <= 0) {
            // We've finished reading the http header.
            break;
        }
    }

    byte[] headerBytes = baos.toByteArray();
    // Save off where content body, post content headers, starts.
    this.contentHeadersLength = headerBytes.length;
    ByteArrayInputStream bais = new ByteArrayInputStream(headerBytes);
    if (!bais.markSupported()) {
        throw new IOException("ByteArrayInputStream does not support mark");
    }
    bais.mark(headerBytes.length);
    // Read the status line.  Don't let it into the parseHeaders function.
    // It doesn't know what to do with it.
    bais.read(statusBytes, 0, statusBytes.length);
    this.contentHeaders = LaxHttpParser.parseHeaders(bais, ARCConstants.DEFAULT_ENCODING);
    bais.reset();
    return bais;
}

From source file:com.remobile.file.LocalFilesystem.java

@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary)
        throws IOException, NoModificationAllowedException {

    boolean append = false;
    if (offset > 0) {
        this.truncateFileAtURL(inputURL, offset);
        append = true;//  ww w. j a va2s  . c  o m
    }

    byte[] rawData;
    if (isBinary) {
        rawData = Base64.decode(data, Base64.DEFAULT);
    } else {
        rawData = data.getBytes();
    }
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);
    try {
        byte buff[] = new byte[rawData.length];
        String absolutePath = filesystemPathForURL(inputURL);
        FileOutputStream out = new FileOutputStream(absolutePath, append);
        try {
            in.read(buff, 0, buff.length);
            out.write(buff, 0, rawData.length);
            out.flush();
        } finally {
            // Always close the output
            out.close();
        }
        if (isPublicDirectory(absolutePath)) {
            broadcastNewFile(Uri.fromFile(new File(absolutePath)));
        }
    } catch (NullPointerException e) {
        // This is a bug in the Android implementation of the Java Stack
        NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
        throw realException;
    }

    return rawData.length;
}