Get a string with default encoding from a stream - Android File Input Output

Android examples for File Input Output:InputStream

Description

Get a string with default encoding from a stream

Demo Code


//package com.java2s;

import java.io.InputStream;

public class Main {
    /**//from  ww  w .j a v  a2 s .c o m
     * Get a string with default encoding from a stream From: http://stackoverflow
     * .com/a/5445161/1266551
     *
     * @param is
     *
     * @return
     */
    public static String getAsString(InputStream is) {
        if (is == null) {
            return null;
        }
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : null;
    }

    /**
     * Get a string with a specific encoding from a stream http://stackoverflow.com/a/5445161/1266551
     *
     * @param is
     * @param encoding
     *
     * @return
     */
    public static String getAsString(InputStream is, String encoding) {
        if (is == null) {
            return null;
        }
        java.util.Scanner s = new java.util.Scanner(is, encoding)
                .useDelimiter("\\A");
        return s.hasNext() ? s.next() : null;
    }
}

Related Tutorials