Example usage for java.io ByteArrayOutputStream toString

List of usage examples for java.io ByteArrayOutputStream toString

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream toString.

Prototype

public synchronized String toString() 

Source Link

Document

Converts the buffer's contents into a string decoding bytes using the platform's default character set.

Usage

From source file:Main.java

public static String readFromAsstes(Context context, String fileName) {
    AssetManager assetManager = context.getAssets();
    ByteArrayOutputStream bos = null;
    InputStream inputStream = null;
    String result = null;/*  w w  w.  j a va 2 s .  c  om*/
    try {
        inputStream = assetManager.open(fileName, AssetManager.ACCESS_STREAMING);
        bos = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int length;
        while ((length = inputStream.read(data)) != -1) {
            bos.write(data, 0, length);
        }
        result = bos.toString().replaceAll("\\s*", "");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            if (bos != null)
                bos.close();
            if (inputStream != null)
                inputStream.close();
        } catch (IOException ignored) {
        }
    }
    return result;
}

From source file:net.ishchenko.idea.nginx.platform.NginxCompileParametersExtractor.java

/**
 * Runs file with -V argument and matches the output against OUTPUT_PATTERN.
 * @param from executable to be run with -V command line argument
 * @return Parameters parsed out from process output
 * @throws PlatformDependentTools.ThisIsNotNginxExecutableException if file could not be run, or
 * output would not match against expected pattern
 *///  ww  w .  ja  va2s .c o m
public static NginxCompileParameters extract(VirtualFile from)
        throws PlatformDependentTools.ThisIsNotNginxExecutableException {

    NginxCompileParameters result = new NginxCompileParameters();

    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    try {
        executor.setStreamHandler(new PumpStreamHandler(os, os));
        executor.execute(CommandLine.parse(from.getPath() + " -V"));
    } catch (IOException e) {
        throw new PlatformDependentTools.ThisIsNotNginxExecutableException(e);
    }

    String output = os.toString();
    Matcher versionMatcher = Pattern.compile("nginx version: nginx/([\\d\\.]+)").matcher(output);
    Matcher configureArgumentsMatcher = Pattern.compile("configure arguments: (.*)").matcher(output);

    if (versionMatcher.find() && configureArgumentsMatcher.find()) {

        String version = versionMatcher.group(1);
        String params = configureArgumentsMatcher.group(1);

        result.setVersion(version);

        Iterable<String> namevalues = StringUtil.split(params, " ");
        for (String namevalue : namevalues) {
            int eqPosition = namevalue.indexOf('=');
            if (eqPosition == -1) {
                handleFlag(result, namevalue);
            } else {
                handleNameValue(result, namevalue.substring(0, eqPosition),
                        namevalue.substring(eqPosition + 1));
            }
        }

    } else {
        throw new PlatformDependentTools.ThisIsNotNginxExecutableException(
                NginxBundle.message("run.configuration.outputwontmatch"));
    }

    return result;

}

From source file:edu.cornell.mannlib.semservices.util.XMLUtils.java

@SuppressWarnings("deprecation")
public static String serializeDoctoString(Document doc) throws IOException {
    org.apache.xml.serialize.XMLSerializer serializer = new org.apache.xml.serialize.XMLSerializer();
    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    serializer.setOutputByteStream(bout);
    serializer.serialize(doc);//from w  w  w.j  ava2 s.  c om
    return bout.toString();
}

From source file:com.mnt.base.util.HttpUtil.java

public static String readData(InputStream in) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int len = 0;//w w  w  .  j a v a  2s.  com
    byte[] buff = new byte[1024];
    while ((len = in.read(buff)) > 0) {
        bos.write(buff, 0, len);
    }

    String result = bos.toString();
    bos.close();

    return result;
}

From source file:Main.java

public static String decompress(String hexString) throws UnsupportedEncodingException {
    final byte[] byteArray = new byte[hexString.length() / 2];
    int k = 0;//from  w  ww.  ja  va2  s  .c o m
    for (int i = 0; i < byteArray.length; i++) {
        byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
        byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
        byteArray[i] = (byte) (high << 4 | low);
        k += 2;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(byteArray);

    try {
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return out.toString();
}

From source file:net.sf.ginp.util.GinpUtil.java

/**
 * Reads the input stream into memory.//from  ww w  .  j  a  v  a  2 s.  c o m
 * @param stream the stream
 * @return a reader for the string represeting the data read
 * from the input stream
 * @throws IOException
 */
public static String readBufferIntoMemory(final InputStream stream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] bufferIn = new byte[4096];
    int readIn = 0;

    while ((readIn = stream.read(bufferIn)) >= 0) {
        baos.write(bufferIn, 0, readIn);
    }

    return baos.toString();
}

From source file:burstcoin.jminer.core.checker.util.OCLChecker.java

public static String readInputStreamAsString(InputStream in) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while (result != -1) {
        byte b = (byte) result;
        buf.write(b);/*from   w  w  w  .ja  va2s. c o m*/
        result = bis.read();
    }
    return buf.toString();
}

From source file:Main.java

private static String readTextFile(InputStream inputStream) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte buf[] = new byte[1024];
    int len;//ww  w .  ja  v a 2s  .  co  m
    try {
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {
        Log.i("IO error", e.getMessage());
        return "Sorry, help file not found.";
    }
    return outputStream.toString();
}

From source file:com.jaeksoft.searchlib.util.PdfCrack.java

public final static String findPassword(String pdfCrackCommandLine, File file)
        throws ExecuteException, IOException {
    ByteArrayOutputStream out = null;
    ByteArrayOutputStream err = null;
    BufferedReader br = null;/*from w  w  w.j av  a 2  s .co  m*/
    try {
        out = new ByteArrayOutputStream();
        err = new ByteArrayOutputStream();
        ExecuteUtils.command(null, pdfCrackCommandLine, null, false, out, err, 3600000L, "-f",
                StringUtils.fastConcat("\"", file.getAbsolutePath(), "\""));
        br = new BufferedReader(new StringReader(out.toString()));
        String line;
        int start = FOUND_USER_PASSWORD.length();
        while ((line = br.readLine()) != null) {
            if (line.startsWith(FOUND_USER_PASSWORD)) {
                int end = line.length() - 1;
                return end == start ? "" : line.substring(start, end);
            }
        }
        return null;
    } finally {
        IOUtils.close(out, err, br);
    }
}

From source file:com.halseyburgund.roundware.server.RWHttpManager.java

public static String uploadFile(String page, Properties properties, String fileParam, String file)
        throws Exception {
    if (D) {/*w ww.  jav a2s  . c om*/
        RWHtmlLog.i(TAG, "Starting upload of file: " + file, null);
    }

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(page);
    MultipartEntity entity = new MultipartEntity();

    Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        entity.addPart(key, new StringBody(val));
        if (D) {
            RWHtmlLog.i(TAG, "Added StringBody multipart for: '" + key + "' = '" + val + "'", null);
        }
    }

    File upload = new File(file);
    entity.addPart(fileParam, new FileBody(upload));
    if (D) {
        String msg = "Added FileBody multipart for: '" + fileParam + "' = <'" + upload.getAbsolutePath()
                + ", size: " + upload.length() + " bytes >'";
        RWHtmlLog.i(TAG, msg, null);
    }

    request.setEntity(entity);

    if (D) {
        RWHtmlLog.i(TAG, "Sending HTTP request...", null);
    }

    HttpResponse response = httpClient.execute(request);

    int st = response.getStatusLine().getStatusCode();

    if (st == HttpStatus.SC_OK) {
        StringBuffer sbResponse = new StringBuffer();
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
            sbResponse.append(line);
        }
        content.close(); // this will also close the connection

        if (D) {
            RWHtmlLog.i(TAG, "Upload successful (HTTP code: " + st + ")", null);
            RWHtmlLog.i(TAG, "Server response: " + sbResponse.toString(), null);
        }

        return sbResponse.toString();
    } else {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);
        RWHtmlLog.e(TAG, "Upload failed (http code: " + st + ")", null);
        RWHtmlLog.e(TAG, "Server response: " + ostream.toString(), null);
        throw new Exception(HTTP_POST_FAILED + st);
    }
}