Java Code Examples for java.io.InputStreamReader.read()

The following are Jave code examples for showing how to use read() of the java.io.InputStreamReader class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ChronoBike   File: StreamUtil.java   View Source Code Vote up 7 votes
/**
 * Convert an InputStream in a String
 *
 * @param inputStream InputStream to convert
 *
 * @return String with the content of InputStream
 *
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
public static String getStringFromInputStream(InputStream inputStream) throws UnsupportedEncodingException, IOException {
  
 InputStreamReader inputTxtStream = new InputStreamReader(inputStream, "ISO-8859-1");

  String StrTemp = "";

  if (inputTxtStream != null) {
    final int DATA_BLOCK_SIZE = 2048;

    // Create the byte array to hold the data
    char[] bytes = new char[DATA_BLOCK_SIZE];

    // Read in the bytes
    int numRead = 0;

    while ((numRead = inputTxtStream.read(bytes, 0, bytes.length)) >= 0) {
      StrTemp += new String(bytes, 0, numRead);
    }
  }

  return StrTemp;
}
 
Example 2
Project: ChronoBike   File: StreamUtil.java   View Source Code Vote up 7 votes
/**
   * Convert a file to a String using specified encoding ("UTF-8", "UTF-16", "latin1", ...)
   * 
   * @param String filePath, String charset
   * 
   * @return String
   * 
   * @throws UnsupportedEncodingException, IOException
   */
public static String getStringFromFile(String filePath, String charset) throws Exception {

	File file = new File(filePath);
	String str = null;
	int numRead = 0;
	final int DATA_BLOCK_SIZE = 2048;
	
	InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charset);

    if (isr != null) {

      // Create the byte array to hold the data
      char[] charArray = new char[DATA_BLOCK_SIZE];

      while ((numRead = isr.read(charArray, 0, DATA_BLOCK_SIZE)) >= 0) {
        str += new String(charArray, 0, numRead);
      }
      isr.close();
    }

    return str;
}
 
Example 3
Project: FJ-VDMJ   File: BacktrackInputReader.java   View Source Code Vote up 7 votes
/**
 * Create an object to read the file name passed with the given charset.
 *
 * @param file	The filename to open
 */

public BacktrackInputReader(File file, String charset)
{
	try
	{
		InputStreamReader isr = readerFactory(file, charset);
		data = new char[readerLength(file, isr)];
		max = isr.read(data);
		pos = 0;
		isr.close();
	}
	catch (IOException e)
	{
		throw new InternalException(0, e.getMessage());
	}
}
 
Example 4
Project: Xndroid   File: ShellUtils.java   View Source Code Vote up 7 votes
private static void checkRoot() {
    sRoot = false;
    char[] buff = new char[1024];
    try {
        Process process = Runtime.getRuntime().exec("su");
        OutputStreamWriter output = new OutputStreamWriter(process.getOutputStream());
        InputStreamReader input = new InputStreamReader(process.getInputStream());
        String testStr = "ROOT_TEST";
        output.write("echo " + testStr + "\n");
        output.flush();
        output.write("exit\n");
        output.flush();
        process.waitFor();
        int count = input.read(buff);
        if (count > 0) {
            if (new String(buff, 0, count).startsWith(testStr))
                sRoot = true;
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 5
Project: Logisim   File: Template.java   View Source Code Vote up 7 votes
public static Template create(InputStream in) {
	InputStreamReader reader = new InputStreamReader(in);
	char[] buf = new char[4096];
	StringBuilder dest = new StringBuilder();
	while (true) {
		try {
			int nbytes = reader.read(buf);
			if (nbytes < 0)
				break;
			dest.append(buf, 0, nbytes);
		} catch (IOException e) {
			break;
		}
	}
	return new Template(dest.toString());
}
 
Example 6
Project: RollenspielAlexaSkill   File: TextUtil.java   View Source Code Vote up 7 votes
public static String readFully(InputStreamReader in) {
	if (in == null) {
		return null;
	}
	try {
		StringWriter result = new StringWriter();
		char[] cbuf = new char[4096];
		int cnt;
		while ((cnt=in.read(cbuf)) > 0) {
			result.write(cbuf, 0, cnt);
		}
		return result.toString();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	finally {
		try {
			in.close();
		} catch (IOException ignore) {}
	}
}
 
Example 7
Project: asw   File: KeyboardKiller.java   View Source Code Vote up 7 votes
public void run() {
       /* interrompe il controllato se l'utente preme INVIO */
       logger.info("KeyboardKiller: Press ENTER to cancel task(s).");
	/* aspetta che l'utente prima INVIO */ 
	InputStreamReader inputStreamReader = new InputStreamReader(System.in);
	char answer = '\0'; 
	while (answer=='\0') {
           try {
               answer = (char) inputStreamReader.read();
           } catch (IOException e) {
               logger.info(this.toString() + ": I/O exception: " + e.toString());
           }
	}
	/* ok, ora interrompe i controllati */
	this.cancel(); 
}
 
Example 8
Project: parabuild-ci   File: StringConverter.java   View Source Code Vote up 7 votes
/**
 * Using a Reader and a Writer, returns a String from an InputStream.
 */
public static String inputStreamToString(InputStream x,
        int length) throws IOException {

    InputStreamReader in        = new InputStreamReader(x);
    StringWriter      writer    = new StringWriter();
    int               blocksize = 8 * 1024;
    char[]            buffer    = new char[blocksize];

    for (int left = length; left > 0; ) {
        int read = in.read(buffer, 0, left > blocksize ? blocksize
                                                       : left);

        if (read == -1) {
            break;
        }

        writer.write(buffer, 0, read);

        left -= read;
    }

    writer.close();

    return writer.toString();
}
 
Example 9
Project: iStudent   File: StateDemo.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws IOException {
    InputStreamReader is = new InputStreamReader( System.in );
    Button btn = new Button();
    while (true) {
        System.out.print("Press 'Enter'");
        is.read();
        btn.push();
    }
}
 
Example 10
Project: JSpark   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * High performance read from an {@link InputStream} into a String
 * 
 * @param inputStream
 *            the input stream from which to read
 * @return the string read from the reader
 * @throws IOException
 *             if an IOException occurs
 */
private static String readStream(InputStream inputStream) throws IOException {
	InputStreamReader reader = new InputStreamReader(inputStream);
	StringWriter sw = new StringWriter();
	char[] buffer = new char[BUFFER_SIZE];
	int pos = 0;
	while ((pos = reader.read(buffer)) != -1) {
		sw.write(buffer, 0, pos);
	}
	return sw.toString();
}
 
Example 11
Project: sstore-soft   File: SnapshotUtil.java   View Source Code Vote up 6 votes
/**
 * Check if the CRC of the snapshot file matches the digest.
 * @param f The snapshot file object
 * @return The table list as a string
 * @throws IOException If CRC does not match
 */
public static String CRCCheck(File f) throws IOException {
    final FileInputStream fis = new FileInputStream(f);
    try {
        final BufferedInputStream bis = new BufferedInputStream(fis);
        ByteBuffer crcBuffer = ByteBuffer.allocate(4);
        if (4 != bis.read(crcBuffer.array())) {
            throw new EOFException("EOF while attempting to read CRC from snapshot digest");
        }
        final int crc = crcBuffer.getInt();
        final InputStreamReader isr = new InputStreamReader(bis, "UTF-8");
        CharArrayWriter caw = new CharArrayWriter();
        while (true) {
            int nextChar = isr.read();
            if (nextChar == -1) {
                throw new EOFException("EOF while reading snapshot digest");
            }
            if (nextChar == '\n') {
                break;
            }
            caw.write(nextChar);
        }
        String tableList = caw.toString();
        byte tableListBytes[] = tableList.getBytes("UTF-8");
        CRC32 tableListCRC = new CRC32();
        tableListCRC.update(tableListBytes);
        tableListCRC.update("\n".getBytes("UTF-8"));
        final int calculatedValue = (int)tableListCRC.getValue();
        if (crc != calculatedValue) {
            throw new IOException("CRC of snapshot digest did not match digest contents");
        }

        return tableList;
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {}
    }
}
 
Example 12
Project: s-store   File: SnapshotUtil.java   View Source Code Vote up 6 votes
/**
 * Check if the CRC of the snapshot file matches the digest.
 * @param f The snapshot file object
 * @return The table list as a string
 * @throws IOException If CRC does not match
 */
public static String CRCCheck(File f) throws IOException {
    final FileInputStream fis = new FileInputStream(f);
    try {
        final BufferedInputStream bis = new BufferedInputStream(fis);
        ByteBuffer crcBuffer = ByteBuffer.allocate(4);
        if (4 != bis.read(crcBuffer.array())) {
            throw new EOFException("EOF while attempting to read CRC from snapshot digest");
        }
        final int crc = crcBuffer.getInt();
        final InputStreamReader isr = new InputStreamReader(bis, "UTF-8");
        CharArrayWriter caw = new CharArrayWriter();
        while (true) {
            int nextChar = isr.read();
            if (nextChar == -1) {
                throw new EOFException("EOF while reading snapshot digest");
            }
            if (nextChar == '\n') {
                break;
            }
            caw.write(nextChar);
        }
        String tableList = caw.toString();
        byte tableListBytes[] = tableList.getBytes("UTF-8");
        CRC32 tableListCRC = new CRC32();
        tableListCRC.update(tableListBytes);
        tableListCRC.update("\n".getBytes("UTF-8"));
        final int calculatedValue = (int)tableListCRC.getValue();
        if (crc != calculatedValue) {
            throw new IOException("CRC of snapshot digest did not match digest contents");
        }

        return tableList;
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {}
    }
}
 
Example 13
Project: ciguan   File: AsDictionaryHandler.java   View Source Code Vote up 6 votes
protected void parse(String pPath) {
    try {
        char[] tBytes = new char[1024];
        StringBuilder tBuffer = new StringBuilder();
        InputStream tStream = getClass().getResourceAsStream(pPath);
        if (tStream == null) {
            tStream = ClassLoader.getSystemResourceAsStream(pPath);
        }
        if (tStream == null) {
            tStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pPath);
        }
        InputStreamReader tReader = new InputStreamReader(tStream, "UTF-8");
        int tCount = tReader.read(tBytes);
        while (tCount > 0) {
            tBuffer.append(new String(tBytes, 0, tCount));
            tCount = tReader.read(tBytes);
        }

        String[] tArr = tBuffer.toString().split("\n");

        createLanguages(tArr[0]);
        for (int i = 1; i < tArr.length; i++) {
            if (tArr[i].indexOf(DELIMITER) > 0) {
                createWord(tArr[i].split(DELIMITER));
            }
        }
        tStream.close();
    }
    catch (Exception e) {
        throw new RuntimeException("Failed to parse dictionary: " + pPath, e);
    }
}
 
Example 14
Project: adyo-android   File: AdyoRestRequest.java   View Source Code Vote up 6 votes
private static String getStringFromInputStream(InputStream stream) throws IOException {
    int n = 0;
    char[] buffer = new char[1024 * 4];
    InputStreamReader reader = new InputStreamReader(stream, "UTF8");
    StringWriter writer = new StringWriter();
    while (-1 != (n = reader.read(buffer))) writer.write(buffer, 0, n);
    return writer.toString();
}
 
Example 15
Project: SpigotNativePlugin   File: ChocoTest.java   View Source Code Vote up 6 votes
private void linkUnix() throws IOException {
    File so = new File(getDataFolder(), "ChocoTest.so");
    if(!so.exists()) {
        FileWriter wr = new FileWriter(so);
        InputStreamReader in = new InputStreamReader(this.getClass().getResourceAsStream("ChocoTest.so"));
        int i;
        while((i = in.read()) != -1) {
            wr.write(i);
        }
    }
    System.load(so.getAbsolutePath());
}
 
Example 16
Project: oma-riista-android   File: TextTask.java   View Source Code Vote up 6 votes
protected String streamToString(InputStream is) throws Exception
{
    String encoding = mTextEncoding;
    if (encoding == null) {
        encoding = mHeaderEncoding;
        if (encoding == null) {
            //Use the default encoding. This is not very optimal, but there is not
            //much that can be done about it.
            encoding = DEFAULT_ENCODING;    
        }
    }
    
    //Try to preallocate the string builder. It is ok if this is huge, we will
    //probably get an out of memory exception and fail gracefully.
    int sizeHint = (int)mContentLength;
    if (sizeHint < 0) {
        sizeHint = 1024;
    }
    
    char[] buffer = new char[BUFFER_SIZE];
    InputStreamReader reader = new InputStreamReader(is, encoding);
    StringBuilder result = new StringBuilder(sizeHint);
    
    int count = 0;
    while ((count = reader.read(buffer, 0, buffer.length)) >= 0) {
        result.append(buffer, 0, count);
    }
    return result.toString();
}
 
Example 17
Project: FJ-VDMJ   File: CommandLine.java   View Source Code Vote up 5 votes
protected String promptLine() throws IOException
{
	if (startLine != null)
	{
		String line = startLine.trim();
		println("> " + startLine);
		startLine = null;
		return line;
	}

	StringBuilder lineTyped = new StringBuilder();
	InputStreamReader console = new InputStreamReader(System.in);
	boolean prompted = false;

	if (messages.isEmpty())
	{
		print(getPrompt());		// Otherwise nothing appears when quiet!
		prompted = true;
	}

	while (true)
	{
		if (!messages.isEmpty())
		{
			if (prompted)
			{
				print("\n");
			}

			while (!messages.isEmpty())
			{
				String msg = messages.poll();

				if (msg.length() > 0)
				{
					println(msg.toString());
				}
			}

			print(getPrompt());
			print(lineTyped.toString());
			prompted = true;
		}

		while (console.ready())
		{
			int c = console.read();

			if (c == '\r')
			{
				continue;
			}
			else if (c == '\n' || c == -1)
			{
				return lineTyped.toString().trim();
			}
			else
			{
				lineTyped.append((char)c);
			}
		}

		Utils.milliPause(10);
	}
}
 
Example 18
Project: QuranKeyboard   File: QuranSearch.java   View Source Code Vote up 5 votes
private void readFile() throws IOException
    {
        /*
         // Scanner is slow as it tests input to search for delimiter
         quran = new Scanner(is).useDelimiter("\\Z").next();
        */

       /*
        // Using zipped quran.txt to save 500kb isn't worth the latency of unzipping it here
        ZipInputStream zi = new ZipInputStream(ime.getResources().openRawResource(R.raw.quran));
        if (zi.getNextEntry() != null) {
            InputStreamReader in = new InputStreamReader(zi, StandardCharsets.UTF_8);
            while (EOF != (n = in.read(buffer))) {
                sb.append(buffer, 0, n);
                count += n;
            }
        }
         */

        /*
        Next is a from apache commons io IOUtils.toString v 2.5
        https://github.com/apache/commons-io/blob/commons-io-2.5/src/main/java/org/apache/commons/io/IOUtils.java
        */
        int n;
//        long count = 0;

//        long start = System.nanoTime();
        char [] buffer = new char[DEF_BUFFER_SIZE];
        StringBuilder sb = new StringBuilder();

        InputStream is = ime.getResources().openRawResource(R.raw.quran);
        InputStreamReader in = new InputStreamReader(is, StandardCharsets.UTF_8);
        while (EOF != (n = in.read(buffer))) {
            sb.append(buffer, 0, n);
//            count += n;
        }
//        long stop = System.nanoTime();
        quran = sb.toString();

//        System.out.println("//////////////////////////////////");
//        System.out.println("Read " + count + " characters, in " +
//                (stop - start) / 1000 + " microseconds\t" +
//                "Quran text length = " + quran.length());
    }
 
Example 19
Project: incubator-netbeans   File: HTMLJavadocParser.java   View Source Code Vote up 4 votes
private static String getTextFromURLStream(JavadocHelper.TextStream page, int[] offsets, String charset) throws IOException {
    if (page == null)
        return null;

    InputStream fis = null;
    InputStreamReader fisreader = null;
    try {
        fis = page.openStream();
        fisreader = charset == null ? new InputStreamReader(fis) : new InputStreamReader(fis, charset);
        
        StringBuilder sb = new StringBuilder();
        int offset = 0;

        for (int i = 0; i < offsets.length - 1; i+=2) {
            int startOffset = offsets[i];
            int endOffset = offsets[i + 1];
            if (startOffset < 0 || endOffset < 0)
                continue;
            if (startOffset > endOffset) {
                LOG.log(Level.WARNING,
                        "Was not able to correctly parse javadoc: {0}, startOffset={1}, endOffset={2}.",
                        new Object[] {page.getLocation(), startOffset, endOffset});
                return null;
            }

            int len = endOffset - startOffset;
            char buffer[] = new char[len];
            int bytesToSkip = startOffset - offset;
            long bytesSkipped = 0;
            do {
                bytesSkipped = fisreader.skip(bytesToSkip);
                bytesToSkip -= bytesSkipped;
            } while ((bytesToSkip > 0) && (bytesSkipped > 0));

            int bytesAlreadyRead = 0;
            do {
                int count = fisreader.read(buffer, bytesAlreadyRead, len - bytesAlreadyRead);
                if (count < 0){
                    break;
                }
                bytesAlreadyRead += count;
            } while (bytesAlreadyRead < len);
            sb.append(buffer);
            offset = endOffset;
        }
        return sb.toString();
    } finally {
        if (fisreader != null)
            fisreader.close();
    }
}
 
Example 20
Project: Elasticsearch   File: LocalRestChannel.java   View Source Code Vote up 4 votes
@Override
public void doSendResponse(RestResponse response) {
    status = response.status().getStatus();

    byte[] bytes = response.content().toBytes();
    long length = bytes.length;
    Args.check(length <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory");
    if(length < 0) {
        length = 4096;
    }

    InputStream instream =  new ByteArrayInputStream(bytes);
    InputStreamReader reader = new InputStreamReader(instream, Consts.UTF_8);
    CharArrayBuffer buffer = new CharArrayBuffer((int)length);
    char[] tmp = new char[1024];

    int l;
    try {
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        content = buffer.toString();
    } catch (IOException e) {
        status = RestStatus.INTERNAL_SERVER_ERROR.getStatus();
        content = "IOException: " + e.getMessage();
    } finally {
        try {
            reader.close();
            instream.close();
        } catch (IOException e1) {
            content = "IOException: " + e1.getMessage();
        } finally {
            count.countDown();
        }
    }
}