Java Code Examples for java.io.Reader#read()

The following examples show how to use java.io.Reader#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StreamUtil.java    From goclipse with Eclipse Public License 1.0 6 votes vote down vote up
/** Reads and returns all chars from given reader until an EOF is read.
 * Closes reader afterwards. */
public static CharArrayWriter readAllCharsFromReader(Reader reader) throws IOException {
	try {
		final int BUFFER_SIZE = 1024;
		char[] buffer = new char[BUFFER_SIZE];
		CharArrayWriter chars = new CharArrayWriter();
		
		int read;
		while((read = reader.read(buffer)) != EOF) {
			chars.write(buffer, 0, read);
		}
		return chars;
	} finally {
		reader.close();
	}
}
 
Example 2
Source File: Matcher.java    From jtransc with Apache License 2.0 6 votes vote down vote up
@GwtIncompatible
public void setAll(Reader in) throws IOException {
    char[] mychars = data;
    int free;
    if (mychars == null || shared) {
        mychars = new char[free = 1024];
    } else free = mychars.length;
    int count = 0;
    int c;
    while ((c = in.read(mychars, count, free)) >= 0) {
        free -= c;
        count += c;
        if (free == 0) {
            int newsize = count * 3;
            char[] newchars = new char[newsize];
            System.arraycopy(mychars, 0, newchars, 0, count);
            mychars = newchars;
            free = newsize - count;
        }
    }
    setTarget(mychars, 0, count, false);
}
 
Example 3
Source File: EncodingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Compares content of document and reader
 */
private static void compareDoc (Reader r, Document doc) throws Exception {
    for (int i = 0; i < doc.getLength(); i++) {
        String ch = doc.getText (i, 1);
        assertEquals ("Really one char", 1, ch.length());
        
        char fromStream = (char)r.read ();
        if (fromStream != ch.charAt (0) && fromStream == (char)13 && ch.charAt (0) == (char)10) {
            // new line in document is always represented by 13, read next character
            fromStream = (char)r.read ();
        }
        
        
        assertEquals ("Stream and doc should be the same on index " + i, (int)fromStream, (int)ch.charAt (0));
    }
}
 
Example 4
Source File: IOUtils.java    From ToolsFinal with Apache License 2.0 6 votes vote down vote up
/**
 * Copy some or all chars from a large (over 2GB) <code>InputStream</code> to an
 * <code>OutputStream</code>, optionally skipping input chars.
 * <p/>
 * This method uses the provided buffer, so there is no need to use a
 * <code>BufferedReader</code>.
 * <p/>
 *
 * @param input       the <code>Reader</code> to read from
 * @param output      the <code>Writer</code> to write to
 * @param inputOffset : number of chars to skip from input before copying
 *                    -ve values are ignored
 * @param length      : number of chars to copy. -ve means all
 * @param buffer      the buffer to be used for the copy
 * @return the number of chars copied
 * @throws NullPointerException if the input or output is null
 * @throws IOException  if an I/O error occurs
 * @since 2.2
 */
public static long copyLarge(Reader input, Writer output, final long inputOffset, final long length, char[] buffer)
        throws IOException {
    if (inputOffset > 0) {
        skipFully(input, inputOffset);
    }
    if (length == 0) {
        return 0;
    }
    int bytesToRead = buffer.length;
    if (length > 0 && length < buffer.length) {
        bytesToRead = (int) length;
    }
    int read;
    long totalRead = 0;
    while (bytesToRead > 0 && EOF != (read = input.read(buffer, 0, bytesToRead))) {
        output.write(buffer, 0, read);
        totalRead += read;
        if (length > 0) { // only adjust length if not reading to the end
            // Note the cast must work because buffer.length is an integer
            bytesToRead = (int) Math.min(length - totalRead, buffer.length);
        }
    }
    return totalRead;
}
 
Example 5
Source File: JSONDecoder.java    From HTTP-RPC with Apache License 2.0 6 votes vote down vote up
private Number readNumber(Reader reader) throws IOException {
    valueBuilder.setLength(0);

    boolean decimal = false;

    while (c != EOF && (Character.isDigit(c) || c == '.' || c == 'e' || c == 'E' || c == '-')) {
        valueBuilder.append((char)c);

        decimal |= (c == '.');

        c = reader.read();
    }

    Number number;
    if (decimal) {
        number = Double.valueOf(valueBuilder.toString());
    } else {
        number = Long.valueOf(valueBuilder.toString());
    }

    return number;
}
 
Example 6
Source File: IOUtils.java    From scriptella-etl with Apache License 2.0 6 votes vote down vote up
/**
 * Loads a reader content into a string.
 *
 * @param reader    reader to load content from. Closed at the end of the operation.
 * @param maxLength max number of characters to read before throwing a Content Too Long Exception.
 * @return string representation of reader content.
 */
public static String toString(final Reader reader, final long maxLength) throws IOException {
    char cb[] = new char[4096];
    StringBuilder sb = new StringBuilder(cb.length);
    long len = 0;

    try {
        for (int n; (n = reader.read(cb)) >= 0;) {
            len += n;
            if (len > maxLength) {
                throw new IOException("Content too long to fit in memory");
            }
            sb.append(cb, 0, n);
        }
    } finally {
        closeSilently(reader);
    }

    return sb.toString();
}
 
Example 7
Source File: CommandUtil.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
public static String convertStreamToStr(InputStream is) throws IOException {

    if (is != null) {
      Writer writer = new StringWriter();

      char[] buffer = new char[1024];
      try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
          writer.write(buffer, 0, n);
        }
      } finally {
        is.close();
      }
      return writer.toString();
    } else {
      return "";
    }
  }
 
Example 8
Source File: IOUtils.java    From memoir with Apache License 2.0 6 votes vote down vote up
/**
 * Skip characters from an input character stream.
 * This implementation guarantees that it will read as many characters
 * as possible before giving up; this may not always be the case for
 * subclasses of {@link Reader}.
 *
 * @param input  character stream to skip
 * @param toSkip number of characters to skip.
 * @return number of characters actually skipped.
 * @throws IOException              if there is a problem reading the file
 * @throws IllegalArgumentException if toSkip is negative
 * @see Reader#skip(long)
 * @since 2.0
 */
public static long skip(Reader input, long toSkip) throws IOException {
    if (toSkip < 0) {
        throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
    }
    /*
     * N.B. no need to synchronize this because: - we don't care if the buffer is created multiple times (the data
     * is ignored) - we always use the same size buffer, so if it it is recreated it will still be OK (if the buffer
     * size were variable, we would need to synch. to ensure some other thread did not create a smaller one)
     */
    if (SKIP_CHAR_BUFFER == null) {
        SKIP_CHAR_BUFFER = new char[SKIP_BUFFER_SIZE];
    }
    long remain = toSkip;
    while (remain > 0) {
        long n = input.read(SKIP_CHAR_BUFFER, 0, (int) Math.min(remain, SKIP_BUFFER_SIZE));
        if (n < 0) { // EOF
            break;
        }
        remain -= n;
    }
    return toSkip - remain;
}
 
Example 9
Source File: GitTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private static String toString(InputStream is) throws IOException {
	if (is != null) {
		Writer writer = new StringWriter();
		char[] buffer = new char[1024];
		try {
			Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			int n;
			while ((n = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, n);
			}
		} finally {
			is.close();
		}
		return writer.toString();
	}
	return "";
}
 
Example 10
Source File: FileCompare.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Read a bufferedReader into a string, using the default platform encoding.
 * 
 * @param reader to be read in
 * @param bufSize - size of stream, in bytes.  Size in chars is &le; size in bytes, because
 * chars take 1 or more bytes to encode.
 * @return String The contents of the stream.
 * @throws IOException
 *           Various I/O errors.
 *           
 * TODO: This is duplicated from org.apache.uima.internal.util.FileUtils in the uimaj-core
 * package. We can't have a compile dependency on uimaj-core since that introduces a cycle. Not
 * sure what the best way of handling this is.
 */
public static String reader2String(Reader reader, int bufSize) throws IOException {
  char[] buf = new char[bufSize];
  int read_so_far = 0;
  try {
    while (read_so_far < bufSize) {
      int count = reader.read(buf, read_so_far, bufSize - read_so_far);
      if (0 > count) {
        break;
      }
      read_so_far += count;
    }
  } finally {
    reader.close();
  }
  return new String(buf, 0, read_so_far);
}
 
Example 11
Source File: Utils.java    From smart-cache with Apache License 2.0 6 votes vote down vote up
public static String read(Reader reader, int length) {
    try {
        char[] buffer = new char[length];

        int offset = 0;
        int rest = length;
        int len;
        while ((len = reader.read(buffer, offset, rest)) != -1) {
            rest -= len;
            offset += len;

            if (rest == 0) {
                break;
            }
        }

        return new String(buffer, 0, length - rest);
    } catch (IOException ex) {
        throw new IllegalStateException("read error", ex);
    }
}
 
Example 12
Source File: IOUtils.java    From AndroidBase with Apache License 2.0 6 votes vote down vote up
/**
 * Read characters from an input character stream.
 * This implementation guarantees that it will read as many characters
 * as possible before giving up; this may not always be the case for
 * subclasses of {@link Reader}.
 *
 * @param input  where to read input from
 * @param buffer destination
 * @param offset inital offset into buffer
 * @param length length to read, must be >= 0
 * @return actual length read; may be less than requested if EOF was reached
 * @throws IOException if a read error occurs
 * @since 2.2
 */
public static int read(Reader input, char[] buffer, int offset, int length) throws IOException {
    if (length < 0) {
        throw new IllegalArgumentException("Length must not be negative: " + length);
    }
    int remaining = length;
    while (remaining > 0) {
        int location = length - remaining;
        int count = input.read(buffer, offset + location, remaining);
        if (EOF == count) { // EOF
            break;
        }
        remaining -= count;
    }
    return length - remaining;
}
 
Example 13
Source File: TokenReplacingReader.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
private String readAll(Reader r) throws IOException {
    int c;
    StringBuilder bld = new StringBuilder();
    while((c = r.read()) >= 0) {
        bld.append((char)c);
    }

    return bld.toString();
}
 
Example 14
Source File: TextType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object get(ResultSet rs, String name) throws HibernateException, SQLException {

			// Retrieve the value of the designated column in the current row of this
			// ResultSet object as a java.io.Reader object
			Reader charReader = rs.getCharacterStream(name);

			// if the corresponding SQL value is NULL, the reader we got is NULL as well
			if (charReader==null) return null;

			// Fetch Reader content up to the end - and put characters in a StringBuffer
			StringBuffer sb = new StringBuffer();
			try {
				char[] buffer = new char[2048];
				while (true) {
					int amountRead = charReader.read(buffer, 0, buffer.length);
					if ( amountRead == -1 ) break;
					sb.append(buffer, 0, amountRead);
				}
			}
			catch (IOException ioe) {
				throw new HibernateException( "IOException occurred reading text", ioe );
			}
			finally {
				try {
					charReader.close();
				}
				catch (IOException e) {
					throw new HibernateException( "IOException occurred closing stream", e );
				}
			}

			// Return StringBuffer content as a large String
			return sb.toString();
	}
 
Example 15
Source File: OldAndroidBufferedReaderTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static String read(Reader a) throws IOException {
    int r;
    StringBuilder builder = new StringBuilder();
    do {
        r = a.read();
        if (r != -1)
            builder.append((char) r);
    } while (r != -1);
    return builder.toString();
}
 
Example 16
Source File: OffHeapTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static String convertClobToString(Clob clob) throws IOException, 
SQLException{
  Reader reader = clob.getCharacterStream();
  StringBuilder sb = new StringBuilder();
  int ch;
  while( (ch = reader.read()) != -1) {
    sb.append((char)ch);
  }
  return sb.toString();
}
 
Example 17
Source File: DiskLruCache.java    From AndroidDemo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the remainder of 'reader' as a string, closing it when done.
 */
public static String readFully(Reader reader) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        char[] buffer = new char[1024];
        int count;
        while ((count = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, count);
        }
        return writer.toString();
    } finally {
        reader.close();
    }
}
 
Example 18
Source File: IOHelpers.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void copy(Reader reader, Writer writer) {
    char[] buf = new char[8192];
    int n = 0;
    try {
        while ((n = reader.read(buf)) != -1) {
            writer.write(buf, 0, n);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 19
Source File: CSVDecoder.java    From HTTP-RPC with Apache License 2.0 4 votes vote down vote up
private void readValues(Reader reader, ArrayList<String> values, char delimiter) throws IOException {
    int c = reader.read();

    while (c != '\r' && c != '\n' && c != EOF) {
        valueBuilder.setLength(0);

        boolean quoted = false;

        if (c == '"') {
            quoted = true;

            c = reader.read();
        }

        while ((quoted || (c != delimiter && c != '\r' && c != '\n')) && c != EOF) {
            valueBuilder.append((char)c);

            c = reader.read();

            if (c == '"') {
                c = reader.read();

                if (c != '"') {
                    quoted = false;
                }
            }
        }

        if (quoted) {
            throw new IOException("Unterminated quoted value.");
        }

        values.add(valueBuilder.toString());

        if (c == delimiter) {
            c = reader.read();
        }
    }

    if (c == '\r') {
        c = reader.read();

        if (c != '\n') {
            throw new IOException("Improperly terminated record.");
        }
    }
}
 
Example 20
Source File: XmlBeansMarshaller.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public int read() throws IOException {
	Reader rdr = getReader();
	return (rdr != null ? rdr.read() : -1);
}