Java Code Examples for java.io.CharArrayWriter#toCharArray()

The following examples show how to use java.io.CharArrayWriter#toCharArray() . 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: poundSignFilterStream.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private char[] readComment() throws IOException {
	CharArrayWriter cout = new CharArrayWriter();
	boolean endComment = false;
	cout.write( '*' );
	readChar(); // read in the '*'
	while ( !endComment && nextChar != -1 ) {
		cout.write( nextChar );
		if ( nextChar == '*' ) {
			readChar();
			if ( nextChar == '/' ) {
				cout.write( '/' );
				readChar();
				endComment = true;
			}
		} else {
			readChar();
		}
	}
	return cout.toCharArray();
}
 
Example 2
Source File: LineMap.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Filter a stack trace, replacing names.
 */
public void printStackTrace(Throwable e, OutputStream os)
{
  CharArrayWriter writer = new CharArrayWriter();
  PrintWriter pw = new PrintWriter(writer);
  
  e.printStackTrace(pw);

  pw.close();
  char []array = writer.toCharArray();

  CharBuffer cb = filter(array);

  if (os != null) {
    byte []b = cb.toString().getBytes();

    try {
      os.write(b, 0, b.length);
    } catch (IOException e1) {
    }
  } else
    System.out.println(cb);
}
 
Example 3
Source File: LineMap.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Filter a stack trace, replacing names.
 */
public void printStackTrace(Throwable e, PrintWriter os)
{
  CharArrayWriter writer = new CharArrayWriter();
  PrintWriter pw = new PrintWriter(writer);
  
  e.printStackTrace(pw);

  pw.close();
  char []array = writer.toCharArray();

  CharBuffer cb = filter(array);

  if (os != null)
    os.print(cb.toString());
  else
    System.out.println(cb);
}
 
Example 4
Source File: JsonParserTest.java    From gson with Apache License 2.0 6 votes vote down vote up
public void testReadWriteTwoObjects() throws Exception {
  Gson gson = new Gson();
  CharArrayWriter writer = new CharArrayWriter();
  BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one");
  writer.write(gson.toJson(expectedOne).toCharArray());
  BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two");
  writer.write(gson.toJson(expectedTwo).toCharArray());
  CharArrayReader reader = new CharArrayReader(writer.toCharArray());

  JsonReader parser = new JsonReader(reader);
  parser.setLenient(true);
  JsonElement element1 = Streams.parse(parser);
  JsonElement element2 = Streams.parse(parser);
  BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class);
  assertEquals("one", actualOne.stringValue);
  BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class);
  assertEquals("two", actualTwo.stringValue);
}
 
Example 5
Source File: Base64.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
private static char[] readChars(final File file) {
    final CharArrayWriter caw = new CharArrayWriter();
    try {
        final Reader fr = new FileReader(file);
        final Reader in = new BufferedReader(fr);
        int count;
        final char[] buf = new char[16384];
        while ((count = in.read(buf)) != -1) {
            if (count > 0) {
                caw.write(buf, 0, count);
            }
        }
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return caw.toCharArray();
}
 
Example 6
Source File: CachedWriter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public char[] getChars() throws IOException {
    flush();
    if (inmem) {
        if (currentStream instanceof LoadingCharArrayWriter) {
            return ((LoadingCharArrayWriter)currentStream).toCharArray();
        }
        throw new IOException("Unknown format of currentStream");
    }
    // read the file
    try (Reader fin = createInputStreamReader(tempFile)) {
        CharArrayWriter out = new CharArrayWriter((int)tempFile.length());
        char[] bytes = new char[1024];
        int x = fin.read(bytes);
        while (x != -1) {
            out.write(bytes, 0, x);
            x = fin.read(bytes);
        }
        return out.toCharArray();
    }
}
 
Example 7
Source File: JspUtil.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public static char[] removeQuotes(char []chars) {
    CharArrayWriter caw = new CharArrayWriter();
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == '%' && chars[i+1] == '\\' &&
            chars[i+2] == '>') {
            caw.write('%');
            caw.write('>');
            i = i + 2;
        } else {
            caw.write(chars[i]);
        }
    }
    return caw.toCharArray();
}
 
Example 8
Source File: poundSignFilterStream.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private char[] readLineComment() throws IOException {
	CharArrayWriter cout = new CharArrayWriter();
	while ( nextChar != '\r' && nextChar != '\n' && nextChar != -1 ) {
		cout.write( nextChar );
		readChar();
	}
	return cout.toCharArray();
}
 
Example 9
Source File: ModificationResultTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static char[] readFully(Reader reader) throws IOException {
    CharArrayWriter baos = new CharArrayWriter();
    int r;

    while ((r = reader.read()) != (-1)) {
        baos.append((char) r);
    }

    return baos.toCharArray();
}
 
Example 10
Source File: JFCParser.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static String readContent(Reader r) throws IOException {
    CharArrayWriter writer = new CharArrayWriter(1024);
    int count = 0;
    int ch;
    while ((ch = r.read()) != -1) {
        writer.write(ch);
        count++;
        if (count >= MAXIMUM_FILE_SIZE) {
            throw new IOException("Presets with more than " + MAXIMUM_FILE_SIZE + " characters can't be read.");
        }
    }
    return new String(writer.toCharArray());
}
 
Example 11
Source File: tagReader.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public tagReader( Reader _in ) throws IOException {
	curLine		= 1;
	curColumn	= 1;

   //--[ Read the stream into memory as we will be needing
   //--[ to do some look-ahead stuff later on with.		
	CharArrayWriter buffer = new CharArrayWriter();
	
	StreamUtil.copyTo(_in,buffer);
	  
	data  = buffer.toCharArray();
	
	tagStack			= new ArrayList<cfTag>();
	caughtExceptions	= new ArrayList<cfCatchData>();
}
 
Example 12
Source File: URLEncoder.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Encode a string according to RFC 1738.
 * <p/>
 * <quote> "...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed],
 * and reserved characters used for their reserved purposes may be used unencoded within a URL."</quote>
 * <p/>
 * <ul> <li><p>The ASCII characters 'a' through 'z', 'A' through 'Z', and '0' through '9' remain the same.
 * <p/>
 * <li><p>The unreserved characters - _ . ! ~ * ' ( ) remain the same.
 * <p/>
 * <li><p>All other ASCII characters are converted into the 3-character string "%xy", where xy is the two-digit
 * hexadecimal representation of the character code
 * <p/>
 * <li><p>All non-ASCII characters are encoded in two steps: first to a sequence of 2 or 3 bytes, using the UTF-8
 * algorithm; secondly each of these bytes is encoded as "%xx". </ul>
 * <p/>
 * This method was adapted from http://www.w3.org/International/URLUTF8Encoder.java Licensed under
 * http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
 *
 * @param s The string to be encoded
 * @return The encoded string
 */

public static String encode( final String s, String enc )
  throws UnsupportedEncodingException {
  boolean needToChange = false;
  final StringBuffer sbuf = new StringBuffer( s.length() );
  final char[] sChars = s.toCharArray();
  final int len = sChars.length;
  Charset charset = charset = Charset.forName( enc );
  CharArrayWriter charArrayWriter = new CharArrayWriter();

  for ( int i = 0; i < len; ) {
    int c = sChars[ i ];
    if ( dontNeedEncoding.get( c ) ) {
      sbuf.append( (char) c );
      i++;
    } else {    // other ASCII
      // convert to external encoding before hex conversion
      do {
        charArrayWriter.write( c );
                  /*
                   * If this character represents the start of a Unicode
                   * surrogate pair, then pass in two characters. It's not
                   * clear what should be done if a bytes reserved in the
                   * surrogate pairs range occurs outside of a legal
                   * surrogate pair. For now, just treat it as if it were
                   * any other character.
                   */
        if ( c >= 0xD800 && c <= 0xDBFF ) {
                      /*
                        System.out.println(Integer.toHexString(c)
                        + " is high surrogate");
                      */
          if ( ( i + 1 ) < s.length() ) {
            int d = (int) s.charAt( i + 1 );
                          /*
                            System.out.println("\tExamining "
                            + Integer.toHexString(d));
                          */
            if ( d >= 0xDC00 && d <= 0xDFFF ) {
                              /*
                                System.out.println("\t"
                                + Integer.toHexString(d)
                                + " is low surrogate");
                              */
              charArrayWriter.write( d );
              i++;
            }
          }
        }
        i++;
      } while ( i < s.length() && !dontNeedEncoding.get( ( c = (int) s.charAt( i ) ) ) );

      charArrayWriter.flush();
      String str = new String( charArrayWriter.toCharArray() );
      byte[] ba = str.getBytes( charset );
      for ( int j = 0; j < ba.length; j++ ) {
        sbuf.append( '%' );
        char ch = Character.forDigit( ( ba[ j ] >> 4 ) & 0xF, 16 );
        // converting to use uppercase letter as part of
        // the hex value if ch is a letter.
        if ( Character.isLetter( ch ) ) {
          ch -= caseDiff;
        }
        sbuf.append( ch );
        ch = Character.forDigit( ba[ j ] & 0xF, 16 );
        if ( Character.isLetter( ch ) ) {
          ch -= caseDiff;
        }
        sbuf.append( ch );
      }
      charArrayWriter.reset();
      needToChange = true;
    }
  }
  return ( needToChange ? sbuf.toString() : s );
}
 
Example 13
Source File: XLContentDigester.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String getContent(ContentResource contentResource)
{
	CharArrayWriter writer = new CharArrayWriter();
	loadContent(writer, contentResource);
	return new String(writer.toCharArray());
}
 
Example 14
Source File: Log.java    From zencash-swing-wallet-ui with MIT License 4 votes vote down vote up
private static void printMessage(boolean oneTimeOnly, String messageClass, String message,
		                         Throwable t, Object ... args)
{
	// TODO: Too much garbage collection
	for (int i = 0; i < args.length; i++)
	{
		if (args[i] != null)
		{
			message = message.replace("{" + i  + "}", args[i].toString());
		}
	}
	message += " ";
	
	if (oneTimeOnly) // One time messages logged only once!
	{
		if (oneTimeMessages.contains(message))
		{
			return;
		} else
		{
			oneTimeMessages.add(message);
		}
	}
	
	String prefix =
		"[" + Thread.currentThread().getName() + "] " +
	    "[" + (new Date()).toString() + "] ";
	
	messageClass = "[" + messageClass + "] ";
	
	String throwable = "";
	if (t != null)
	{
		CharArrayWriter car = new CharArrayWriter(500);
		PrintWriter pr = new PrintWriter(car);
		pr.println();  // One line extra before the exception.
		t.printStackTrace(pr);
		pr.close();
		throwable = new String(car.toCharArray()); 
	}
		
	System.out.println(prefix + messageClass + message + throwable);
	
	if (fileOut != null)
	{
		fileOut.println(prefix + messageClass + message + throwable);
		fileOut.flush();
	}
}
 
Example 15
Source File: JspReader.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
/**
    * Push a file (and its associated Stream) on the file stack.  THe
    * current position in the current file is remembered.
    */
   private void pushFile(String file, String encoding, 
		   InputStreamReader reader) 
        throws JasperException, FileNotFoundException {

// Register the file
String longName = file;

int fileid = registerSourceFile(longName);

       if (fileid == -1) {
           err.jspError("jsp.error.file.already.registered", file);
}

currFileId = fileid;

try {
    CharArrayWriter caw = new CharArrayWriter();
    char buf[] = new char[1024];
    for (int i = 0 ; (i = reader.read(buf)) != -1 ;)
	caw.write(buf, 0, i);
    caw.close();
    if (current == null) {
	current = new Mark(this, caw.toCharArray(), fileid, 
			   getFile(fileid), master, encoding);
    } else {
	current.pushStream(caw.toCharArray(), fileid, getFile(fileid),
			   longName, encoding);
    }
} catch (Throwable ex) {
    log.log(Level.SEVERE, "Exception parsing file ", ex);
    // Pop state being constructed:
    popFile();
    err.jspError("jsp.error.file.cannot.read", file);
} finally {
    if (reader != null) {
	try {
	    reader.close();
	} catch (Exception any) {}
    }
}
   }
 
Example 16
Source File: IOUtils.java    From aion-germany with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Get the contents of an <code>InputStream</code> as a character array
 * using the specified character encoding.
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedInputStream</code>.
 * 
 * @param is  the <code>InputStream</code> to read from
 * @param encoding  the encoding to use, null means platform default
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException if an I/O error occurs
 * @since 2.3
 */
public static char[] toCharArray(InputStream is, Charset encoding)
        throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output, encoding);
    return output.toCharArray();
}
 
Example 17
Source File: IOUtils.java    From dttv-android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Get the contents of a <code>Reader</code> as a character array.
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 * 
 * @param input  the <code>Reader</code> to read from
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException if an I/O error occurs
 * @since Commons IO 1.1
 */
public static char[] toCharArray(Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}
 
Example 18
Source File: IOUtils.java    From AndroidBase with Apache License 2.0 2 votes vote down vote up
/**
 * Get the contents of a <code>Reader</code> as a character array.
 * <p/>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 *
 * @param input the <code>Reader</code> to read from
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException  if an I/O error occurs
 * @since 1.1
 */
public static char[] toCharArray(Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}
 
Example 19
Source File: IOUtils.java    From jsongood with Apache License 2.0 2 votes vote down vote up
/**
 * Get the contents of a <code>Reader</code> as a character array.
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 * 
 * @param input  the <code>Reader</code> to read from
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException if an I/O error occurs
 * @since 1.1
 */
public static char[] toCharArray(Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}
 
Example 20
Source File: IOUtils.java    From memoir with Apache License 2.0 2 votes vote down vote up
/**
 * Get the contents of a <code>Reader</code> as a character array.
 * <p/>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 *
 * @param input the <code>Reader</code> to read from
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException          if an I/O error occurs
 * @since 1.1
 */
public static char[] toCharArray(Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}