Java Code Examples for java.io.InputStreamReader

The following are top voted examples for showing how to use java.io.InputStreamReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: HttpPageletAdaptor.java View source code Vote up 6 votes
/**
 * Processes the pagelet of the generating page by reading the content from 
 * the pagelet and generates it to the output.
 *   
 * @param element the template element which represents the pagelet.
 * @param pagelet the pagelet to be processed.
 * @param request the servlet request.
 * @param response the servlet response.
 * @throws RequestListenerException if unable to process the pagelet.
 * 
 * @see #processTemplate(HttpServletRequest, HttpServletResponse)
 */

protected void processPagelet(TemplateElement element, Pagelet pagelet, HttpServletRequest request,
        HttpServletResponse response) throws RequestListenerException {
    try {
        if (pagelet != null) {
            InputStreamReader reader = new InputStreamReader(
                    pagelet.openStream(), Charset.forName("UTF-8"));
            IOHandler.pipe(reader, response.getWriter());
            reader.close();
            reader = null;
        }
    }
    catch (Exception e) {
        throw new RequestListenerException("Error in processing pagelet", e);
    }
}
 
Example 2
Project: richfaces   File: SyntaxHighlighter.java View source code Vote up 6 votes
private void renderStream(FacesContext context, InputStream stream) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    InputStreamReader in = new InputStreamReader(stream);
    char[] temp = new char[1024];
    try {
        int bytes;
        while ((bytes = in.read(temp)) > 0) {
            writer.writeText(temp, 0, bytes);
        }
    } catch (IOException e) {
        throw new FacesException(e);
    } finally {
        in.close();
    }
}
 
Example 3
Project: breakout   File: BimapperStreamBimapper.java View source code Vote up 6 votes
@Override
public T read( InputStream in ) throws Exception
{
	InputStreamReader reader = null;
	
	try
	{
		reader = new InputStreamReader( in );
		StringBuffer sb = new StringBuffer( );
		int c;
		
		while( ( c = reader.read( ) ) >= 0 )
		{
			sb.append( ( char ) c );
		}
		return format.unmap( sb.toString( ) );
	}
	finally
	{
		if( closeStreams && reader != null )
		{
			try
			{
				reader.close( );
			}
			catch( Exception ex )
			{
				
			}
		}
	}
}
 
Example 4
Project: BangumiTimeMachine   File: NetWorkTool.java View source code Vote up 6 votes
public static String GZipDecoderToString(byte[] data) {
    GZIPInputStream gzipInputStream = null;
    try {
        gzipInputStream = new GZIPInputStream(
                new ByteArrayInputStream(data));
        InputStreamReader reader = new InputStreamReader(gzipInputStream);
        BufferedReader in = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String read;
        while ((read = in.readLine()) != null){
            sb.append(read);
        }
        String json = sb.toString();
        reader.close();
        in.close();
        gzipInputStream.close();
        return json;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 5
Project: Magnolia   File: BetwixtModuleDefinitionReader.java View source code Vote up 6 votes
@Override
public ModuleDefinition readFromResource(String resourcePath) throws ModuleManagementException {
    final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(resourcePath));
    try {
        return read(reader);
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            log.error("Can't close input for " + resourcePath);
        }
    }
}
 
Example 6
Project: TextSecureSMP   File: PreKeyUtil.java View source code Vote up 6 votes
private static int getNextPreKeyId(Context context) {
  try {
    File nextFile = new File(getPreKeysDirectory(context), PreKeyIndex.FILE_NAME);

    if (!nextFile.exists()) {
      return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
    } else {
      InputStreamReader reader = new InputStreamReader(new FileInputStream(nextFile));
      PreKeyIndex       index  = JsonUtils.fromJson(reader, PreKeyIndex.class);
      reader.close();
      return index.nextPreKeyId;
    }
  } catch (IOException e) {
    Log.w("PreKeyUtil", e);
    return Util.getSecureRandom().nextInt(Medium.MAX_VALUE);
  }
}
 
Example 7
Project: CSharpGrammar   File: ANTLRFileStreamWithBOM.java View source code Vote up 6 votes
public void load(final String fileName, final String encoding) throws IOException {
	if (fileName == null) {
		return;
	}
	File f = new File(fileName);
	long length = f.length();
	if (length > Integer.MAX_VALUE) {
		throw new BufferOverflowException();
	}
	int size = (int) length;

	InputStreamReader isr;
	FileInputStream fis = new FileInputStream(fileName);

	UnicodeBOMInputStream bomInputStream = new UnicodeBOMInputStream(fis);
	bomInputStream.skipBOM();

	if (encoding != null) {
		isr = new InputStreamReader(bomInputStream, encoding);
	} else {
		isr = new InputStreamReader(bomInputStream);
	}

	// bug in ANTLR: what if size is > Integer.MAX_VALUE
	// solution: read content within a loop and with a StringBuilder
	try {
		data = new char[size];
		super.n = isr.read(data);
	} finally {
		isr.close();
	}
}
 
Example 8
Project: cbe   File: FileLoader.java View source code Vote up 6 votes
public List<String> loadLines(String filename)
{
    BufferedReader    bufferedReader    = null;
    InputStream       inputStream       = null;
    InputStreamReader inputStreamReader = null;
    List<String>      lines             = new ArrayList<String>();

    try
    {
        inputStream       = getClass().getClassLoader().getResourceAsStream(filename);
        inputStreamReader = new InputStreamReader(inputStream);
        bufferedReader    = new BufferedReader(inputStreamReader);

        String line = null;

        while ((line = bufferedReader.readLine()) != null)
            lines.add(line);

        inputStream.close();
        inputStreamReader.close();
        bufferedReader.close();
    }
    catch (IOException e)
    {
        System.err.println("Failed to read and/or close file:");
        e.printStackTrace();
    }

    return lines;
}
 
Example 9
Project: NewsSpeakServer   File: SourceTests.java View source code Vote up 6 votes
/**
 * Test that the same characters are returned as with another reader.
 */
public void testSameChars () throws IOException
{
    String link;
    URL url;
    URLConnection connection1;
    URLConnection connection2;
    InputStreamReader in;
    int c1;
    int c2;
    Source source;
    int index;

    link = "http://htmlparser.sourceforge.net";
    try
    {
        url = new URL (link);
        connection1 = url.openConnection ();
        connection1.connect ();
        in = new InputStreamReader (new BufferedInputStream (connection1.getInputStream ()), "UTF-8");
        connection2 = url.openConnection ();
        connection2.connect ();
        source = new InputStreamSource (new Stream (connection2.getInputStream ()), "UTF-8");
        index = 0;
        while (-1 != (c1 = in.read ()))
        {
            c2 = source.read ();
            if (c1 != c2)
                fail ("characters differ at position " + index + ", expected " + c1 + ", actual " + c2);
            index++;
        }
        c2 = source.read ();
        assertTrue ("extra characters", -1 == c2);
        source.close ();
        in.close ();
    }
    catch (MalformedURLException murle)
    {
        fail ("bad url " + link);
    }
}
 
Example 10
Project: avaje-ebeanorm   File: ScalarTypeJsonMap.java View source code Vote up 6 votes
@Override
public Map read(DataReader dataReader) throws SQLException {

  InputStream is = dataReader.getBinaryStream();
  if (is == null) {
    return null;
  }
  try {
    InputStreamReader reader = new InputStreamReader(is);
    try {
      return parse(reader);
    } finally {
      reader.close();
    }
  } catch (IOException e) {
    throw new SQLException("Error reading Blob stream from DB", e);
  }
}
 
Example 11
Project: ExcusePro   File: UrlRedirectCache.java View source code Vote up 6 votes
static URL getRedirectedUrl(Context context, URL url) {
    if (url == null) {
        return null;
    }

    String urlString = url.toString();
    URL finalUrl = null;
    InputStreamReader reader = null;
    try {
        InputStream stream;
        FileLruCache cache = getCache(context);
        boolean redirectExists = false;
        while ((stream = cache.get(urlString, REDIRECT_CONTENT_TAG)) != null) {
            redirectExists = true;

            // Get the redirected url
            reader = new InputStreamReader(stream);
            char[] buffer = new char[128];
            int bufferLength;
            StringBuilder urlBuilder = new StringBuilder();
            while ((bufferLength = reader.read(buffer, 0, buffer.length)) > 0) {
                urlBuilder.append(buffer, 0, bufferLength);
            }
            Utility.closeQuietly(reader);

            // Iterate to the next url in the redirection
            urlString = urlBuilder.toString();
        }

        if (redirectExists) {
            finalUrl = new URL(urlString);
        }
    } catch (MalformedURLException e) {
        // caching is best effort, so ignore the exception
    } catch (IOException ioe) {
    } finally {
        Utility.closeQuietly(reader);
    }

    return finalUrl;
}
 
Example 12
Project: JerseyTest   File: FormDataMultiPartReaderWriterTest.java View source code Vote up 6 votes
private void checkEntity(String expected, BodyPartEntity entity) throws IOException {
    // Convert the raw bytes into a String
    InputStreamReader sr = new InputStreamReader(entity.getInputStream());
    StringWriter sw = new StringWriter();
    while (true) {
        int ch = sr.read();
        if (ch < 0) {
            break;
        }
        sw.append((char) ch);
    }
    // Perform the comparison
    assertEquals(expected, sw.toString());
}
 
Example 13
Project: HugeCollections   File: OSResizesMain.java View source code Vote up 6 votes
static String run(String... cmd) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStreamReader reader = new InputStreamReader(p.getInputStream());
    StringWriter sw = new StringWriter();
    char[] chars = new char[512];
    for (int len; (len = reader.read(chars)) > 0; )
        sw.write(chars, 0, len);
    int exitValue = p.waitFor();
    if (exitValue != 0)
        sw.write("\nexit=" + exitValue);
    p.destroy();
    return sw.toString();
}
 
Example 14
Project: gag   File: FileDescriptor.java View source code Vote up 6 votes
/** Reads the entire file into a string using the specified charset.
 * @throw RuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString (String charset) {
	StringBuilder output = new StringBuilder(512);
	InputStreamReader reader = null;
	try {
		if (charset == null)
			reader = new InputStreamReader(read());
		else
			reader = new InputStreamReader(read(), charset);
		char[] buffer = new char[256];
		while (true) {
			int length = reader.read(buffer);
			if (length == -1) break;
			output.append(buffer, 0, length);
		}
	} catch (IOException ex) {
		throw new RuntimeException("Error reading layout file: " + this, ex);
	} finally {
		try {
			if (reader != null) reader.close();
		} catch (IOException ignored) {
		}
	}
	return output.toString();
}
 
Example 15
Project: BigPangOrderManager   File: HttpHelper.java View source code Vote up 6 votes
private static CharSequence consume(URLConnection connection, int maxChars) throws IOException {
  String encoding = getEncoding(connection);
  StringBuilder out = new StringBuilder();
  Reader in = null;
  try {
    in = new InputStreamReader(connection.getInputStream(), encoding);
    char[] buffer = new char[1024];
    int charsRead;
    while (out.length() < maxChars && (charsRead = in.read(buffer)) > 0) {
      out.append(buffer, 0, charsRead);
    }
  } finally {
    if (in != null) {
      try {
        in.close();
      } catch (IOException ioe) {
        // continue
      } catch (NullPointerException npe) {
        // another apparent Android / Harmony bug; continue
      }
    }
  }
  return out;
}
 
Example 16
Project: visuwall   File: ShowFileAction.java View source code Vote up 6 votes
public ActionForward execute(ActionMapping mapping,
                             ActionForm form,
                             HttpServletRequest request,
                             HttpServletResponse response)
                      throws Exception {

    // Get the file name
    String fileName = mapping.getParameter();
    StringBuffer fileContents = new StringBuffer();

    if(fileName != null) {

        InputStream input = servlet.getServletContext().getResourceAsStream(fileName);
        if (input == null) {
            log.warn("File Not Found: "+fileName);
        } else {
            InputStreamReader inputReader = new InputStreamReader(input);
            char[] buffer = new char[1000];
            while (true) {
                int lth = inputReader.read(buffer);
                if (lth < 0) {
                    break;
                } else {
                    fileContents.append(buffer, 0, lth);
                }
            }
        }
    } else {
        log.error("No file name specified.");
    }


    // Store the File contents and name in the Request
    request.setAttribute("fileName", fileName);
    request.setAttribute("fileContents", fileContents.toString());

    return mapping.findForward("success");
}
 
Example 17
Project: LiveFootball   File: Parser.java View source code Vote up 6 votes
/**
 * This utility method is used to parse comments and XML declarations in the HTML.
 * The comment/declaration is returned as an Element.
 * In the current implementation they will be ommitted from the final DOM (=the root element) as the tag name won't match supported tags.
 *
 * @param is The inputstream
 * @param endTag The endtag to look for
 * @return
 * @throws IOException
 */
private Element parseCommentOrXMLDeclaration(InputStreamReader is,String endTag) throws IOException {
    int endTagPos=0;
    String text="";
    boolean ended=false;
    while (!ended) {
        char c=(char)is.read();
        if (c==endTag.charAt(endTagPos)) {
            endTagPos++;
            if (endTagPos==endTag.length()) {
                ended=true;
            }
        } else {
            if (endTagPos!=0) { //add - or -- if it wasn't an end tag eventually
                text+=endTag.substring(0, endTagPos);
                endTagPos=0;
            }
            text+=c;
        }
    }

    String elementName=null;
    if (endTag.equals("-->")) {
        elementName="comment";
    } else if (endTag.equals(">")) {
        elementName="XML declaration";
    }

    Element comment = new Element(elementName);
    comment.addAttribute("content", text);
    return comment;
}
 
Example 18
Project: NewsSpeakServer   File: InputStreamSource.java View source code Vote up 6 votes
/**
 * Create a source of characters.
 * @param stream The stream of bytes to use.
 * @param charset The character set used in encoding the stream.
 * @param size The initial character buffer size.
 * @exception UnsupportedEncodingException If the character set
 * is unsupported.
 */
public InputStreamSource (InputStream stream, String charset, int size)
    throws
        UnsupportedEncodingException
{
    if (null == stream)
        stream = new Stream (null);
    else
        // bug #1044707 mark()/reset() issues
        if (!stream.markSupported ())
            // wrap the stream so we can reset
            stream = new Stream (stream);
        // else
            // just because mark is supported doesn't guarantee
            // proper reset operation; there is no call to mark
            // in this code, so if reset misbehaves there is an
            // appropriate message in setEncoding() to suggest
            // wraping it in a Stream.
            // This was deemed better than an attempt to call
            // reset at this point just to check if we would
            // succeed later, or to call mark with an arbitrary
            // lookahead size
    mStream = stream;
    if (null == charset)
    {
        mReader = new InputStreamReader (stream);
        mEncoding = mReader.getEncoding ();
    }
    else
    {
        mEncoding = charset;
        mReader = new InputStreamReader (stream, charset);
    }
    mBuffer = new char[size];
    mLevel = 0;
    mOffset = 0;
    mMark = -1;
}
 
Example 19
Project: EclipseTrader   File: InputStreamSource.java View source code Vote up 6 votes
/**
 * Create a source of characters.
 * @param stream The stream of bytes to use.
 * @param charset The character set used in encoding the stream.
 * @param size The initial character buffer size.
 * @exception UnsupportedEncodingException If the character set
 * is unsupported.
 */
public InputStreamSource (InputStream stream, String charset, int size)
    throws
        UnsupportedEncodingException
{
    if (null == stream)
        stream = new Stream (null);
    else
        // bug #1044707 mark()/reset() issues
        if (!stream.markSupported ())
            // wrap the stream so we can reset
            stream = new Stream (stream);
        // else
            // just because mark is supported doesn't guarantee
            // proper reset operation; there is no call to mark
            // in this code, so if reset misbehaves there is an
            // appropriate message in setEncoding() to suggest
            // wraping it in a Stream.
            // This was deemed better than an attempt to call
            // reset at this point just to check if we would
            // succeed later, or to call mark with an arbitrary
            // lookahead size
    mStream = stream;
    if (null == charset)
    {
        mReader = new InputStreamReader (stream);
        mEncoding = mReader.getEncoding ();
    }
    else
    {
        mEncoding = charset;
        mReader = new InputStreamReader (stream, charset);
    }
    mBuffer = new char[size];
    mLevel = 0;
    mOffset = 0;
    mMark = -1;
}
 
Example 20
Project: jxta   File: StringMessageElement.java View source code Vote up 6 votes
/**
 * Returns an appropriate mime type for the given encoding name. The
 * mimetype will contain the canonical name of the encoding.
 *
 * @param encoding name of the desired encoding.
 * @return the mime type.
 * @throws java.io.UnsupportedEncodingException
 *          if the mime is unsupported
 */
private static MimeMediaType makeMimeType(String encoding) throws UnsupportedEncodingException {
    InputStreamReader getEncoding = new InputStreamReader(new ByteArrayInputStream(new byte[0]), encoding);

    String canonicalName = getEncoding.getEncoding();

    return new MimeMediaType(MimeMediaType.TEXT_DEFAULTENCODING, "charset=\"" + canonicalName + "\"", true).intern();
}
 
Example 21
Project: rinzo-xml-editor   File: FileUtils.java View source code Vote up 6 votes
/**
   * Guarda un documento localmente en la cache
   */
  public static void saveFile(String inputFileName, File outputFile) {
InputStream openStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
try {
	File inputFile = new File(inputFileName);
	if (!inputFile.exists()) {
		openStream = new URL(inputFileName).openStream();
		InputStreamReader is = new InputStreamReader(openStream);
		String encoding = is.getEncoding();
		reader = new BufferedReader(is);
		writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile, false), encoding));

		String line = reader.readLine();
		while (line != null) {
			writer.write(line);
			writer.newLine();
			writer.flush();
			line = reader.readLine();
		}
	}
} catch (Exception exception) {
	throw new RuntimeException("Error trying to save \'" + inputFileName + "\' in the cache.", exception);
} finally {
	try {
		if (writer != null) {
			writer.flush();
			writer.close();
		}
		if (reader != null) {
			reader.close();
		}
		if (openStream != null) {
			openStream.close();
		}
	} catch (IOException e) {
		throw new RuntimeException("Error trying to close files while saving \'" + inputFileName
				+ "\' in the cache.", e);
	}
}
  }
 
Example 22
Project: open-mika   File: InputStreamReaderTest.java View source code Vote up 6 votes
public void testGetEncoding_StreamClosed() throws IOException {
    InputStreamReader in = null;
    byte b[] = new byte[5];
    in = new InputStreamReader(new ByteArrayInputStream(b), "UTF-16BE");
    in.close();
    String result = in.getEncoding();
    assertNull(result);
}
 
Example 23
Project: ez-vcard   File: VCardRawReader.java View source code Vote up 6 votes
/**
 * Gets the character encoding of the reader.
 * @return the character encoding or null if none is defined
 */
public Charset getEncoding() {
	if (reader instanceof InputStreamReader) {
		InputStreamReader isr = (InputStreamReader) reader;
		String charsetStr = isr.getEncoding();
		return (charsetStr == null) ? null : Charset.forName(charsetStr);
	}

	return null;
}
 
Example 24
Project: pentaho-kettle   File: TextFileInputReader.java View source code Vote up 6 votes
public TextFileInputReader( IBaseFileInputStepControl step, TextFileInputMeta meta, TextFileInputData data,
    FileObject file, LogChannelInterface log ) throws Exception {
  this.step = step;
  this.meta = meta;
  this.data = data;
  this.log = log;

  CompressionProvider provider =
      CompressionProviderFactory.getInstance().getCompressionProviderByName( meta.content.fileCompression );

  if ( log.isDetailed() ) {
    log.logDetailed( "This is a compressed file being handled by the " + provider.getName() + " provider" );
  }

  in = provider.createInputStream( KettleVFS.getInputStream( file ) );

  in.nextEntry();

  BufferedInputStream inStream = new BufferedInputStream( in, BUFFER_SIZE_INPUT_STREAM );
  BOMDetector bom = new BOMDetector( inStream );

  if ( bom.bomExist() ) {
    // if BOM exist, use it instead defined charset
    isr = new InputStreamReader( inStream, bom.getCharset() );
  } else if ( meta.getEncoding() != null && meta.getEncoding().length() > 0 ) {
    isr = new InputStreamReader( inStream, meta.getEncoding() );
  } else {
    isr = new InputStreamReader( inStream );
  }

  String encoding = isr.getEncoding();
  data.encodingType = EncodingType.guessEncodingType( encoding );

  readInitial();
}
 
Example 25
Project: raven-aws-emr-kissmetrics-mapreduce-parser-redshift   File: KissmetricsRowParser.java View source code Vote up 6 votes
public static String getDefaultCharEncoding() {
	byte[] bArray = { 'w' };
	InputStream is = new ByteArrayInputStream(bArray);
	InputStreamReader reader = new InputStreamReader(is);
	String defaultCharacterEncoding = reader.getEncoding();
	return defaultCharacterEncoding;
}
 
Example 26
Project: htmlparser   File: InputStreamSource.java View source code Vote up 6 votes
/**
 * Create a source of characters.
 * @param stream The stream of bytes to use.
 * @param charset The character set used in encoding the stream.
 * @param size The initial character buffer size.
 * @exception UnsupportedEncodingException If the character set
 * is unsupported.
 */
public InputStreamSource (InputStream stream, String charset, int size)
    throws
        UnsupportedEncodingException
{
    if (null == stream)
        stream = new Stream (null);
    else
        // bug #1044707 mark()/reset() issues
        if (!stream.markSupported ())
            // wrap the stream so we can reset
            stream = new Stream (stream);
        // else
            // just because mark is supported doesn't guarantee
            // proper reset operation; there is no call to mark
            // in this code, so if reset misbehaves there is an
            // appropriate message in setEncoding() to suggest
            // wraping it in a Stream.
            // This was deemed better than an attempt to call
            // reset at this point just to check if we would
            // succeed later, or to call mark with an arbitrary
            // lookahead size
    mStream = stream;
    if (null == charset)
    {
        mReader = new InputStreamReader (stream);
        mEncoding = mReader.getEncoding ();
    }
    else
    {
        mEncoding = charset;
        mReader = new InputStreamReader (stream, charset);
    }
    mBuffer = new char[size];
    mLevel = 0;
    mOffset = 0;
    mMark = -1;
}
 
Example 27
Project: tmdm-studio-se   File: FileUtils.java View source code Vote up 6 votes
/**
 * Guarda un documento localmente en la cache
 */
public static void saveFile(String inputFileName, File outputFile) {
    InputStream openStream = null;
    BufferedReader reader = null;
    BufferedWriter writer = null;
    try {
        File inputFile = new File(inputFileName);
        if (!inputFile.exists()) {
            openStream = new URL(inputFileName).openStream();
            InputStreamReader is = new InputStreamReader(openStream);
            String encoding = is.getEncoding();
            reader = new BufferedReader(is);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile, false), encoding));

            String line = reader.readLine();
            while (line != null) {
                writer.write(line);
                writer.newLine();
                writer.flush();
                line = reader.readLine();
            }
        }
    } catch (Exception exception) {
        throw new RuntimeException("Error trying to save \'" + inputFileName + "\' in the cache.", exception); //$NON-NLS-1$ //$NON-NLS-2$
    } finally {
        try {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (openStream != null) {
                openStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException("Error trying to close files while saving \'" + inputFileName + "\' in the cache.", e); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
}
 
Example 28
Project: swtbot   File: ProjectCreator.java View source code Vote up 6 votes
private String read(InputStream is) {
	StringBuffer buffer = new StringBuffer();
	InputStreamReader in = null;
	try {
		in = new InputStreamReader(is, "utf-8");
		while (in.ready()) {
			buffer.append((char) in.read());
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	} finally {
		close(in);
	}
	return buffer.toString();
}
 
Example 29
Project: pmd-eclipse-plugin   File: ReviewAction.java View source code Vote up 6 votes
public static String readFile(IFile file) throws IOException, CoreException {
    InputStream contents = file.getContents(true);
    InputStreamReader reader = new InputStreamReader(contents);

    try {
        char[] buffer = new char[4096];
        StringBuilder sb = new StringBuilder(4096);
        while (reader.ready()) {
            int readCount = reader.read(buffer);
            if (readCount != -1) {
                sb.append(buffer, 0, readCount);
            }
        }

        return sb.toString();

    } finally {
        reader.close();
    }
}
 
Example 30
Project: JBossAS_5_1_EDG   File: EJBRegistrationDeployer.java View source code Vote up 6 votes
public static boolean has30EjbJarXml(InputStream ddStream)
{
   try
   {
      // look for version="3.0" in the file
      byte[] stringToFind = "version=\"3.0\"".getBytes();
      InputStreamReader reader = new InputStreamReader(ddStream);
      try
      {
         int idx = 0;
         int len = stringToFind.length;
         while (reader.ready())
         {
            int read = reader.read();
            if (read == stringToFind[idx])
            {
               idx++;
               if (idx == len)
               {
                  return true;
               }
            }
            else
            {
               idx = 0;
            }
         }

      }
      finally
      {
         try
         {
            reader.close();
            ddStream.close();
         }
         catch (IOException ignored)
         {
         }
      }
   }
   catch (Exception ignore)
   {
   }
   return false;
}
 
Example 31
Project: Payara   File: SysnetTransferManager.java View source code Vote up 6 votes
/**
 * Copies all available output from the specified reader to the string 
 * builder accumulating a copy of that output.
 * @param reader the InputStreamReader from which to copy
 * @param sb the StringBuilder that holds the accumulated contents of the stream
 */
private void copyFromReader(InputStreamReader reader, StringBuilder sb) throws IOException {
    char[] buffer = new char[INPUT_BUFFER_SIZE];
    boolean eoStream = false;
    while (reader.ready() && ! eoStream) {
        int charsRead = reader.read(buffer);
        if (charsRead == -1) {
            eoStream = true;
        } else {
            sb.append(buffer, 0, charsRead);
        }
    }
}
 
Example 32
Project: enviroCar-app   File: CacheDAOTest.java View source code Vote up 6 votes
protected void prepareCache(File baseFolder, String asset, String assetFile) throws IOException {
	InputStream is = getInstrumentation().getContext().getAssets().open(asset);
	FileWriter fw = new FileWriter(new File(baseFolder, assetFile), false);
	
	InputStreamReader isr = new InputStreamReader(is);
	
	while (isr.ready()) {
		fw.write(isr.read());
	}
	
	fw.flush();
	fw.close();
	isr.close();
}
 
Example 33
Project: JBossAS51   File: EJBRegistrationDeployer.java View source code Vote up 6 votes
public static boolean has30EjbJarXml(InputStream ddStream)
{
   try
   {
      // look for version="3.0" in the file
      byte[] stringToFind = "version=\"3.0\"".getBytes();
      InputStreamReader reader = new InputStreamReader(ddStream);
      try
      {
         int idx = 0;
         int len = stringToFind.length;
         while (reader.ready())
         {
            int read = reader.read();
            if (read == stringToFind[idx])
            {
               idx++;
               if (idx == len)
               {
                  return true;
               }
            }
            else
            {
               idx = 0;
            }
         }

      }
      finally
      {
         try
         {
            reader.close();
            ddStream.close();
         }
         catch (IOException ignored)
         {
         }
      }
   }
   catch (Exception ignore)
   {
   }
   return false;
}
 
Example 34
Project: ktop   File: KTop.java View source code Vote up 6 votes
private boolean waitOnKeyboard() throws InterruptedException {
    InputStreamReader reader = new InputStreamReader(session.getKeyboard());
    for (int i = 0; i < DEFAULT_REFRESH_INTERVAL / DEFAULT_KEYBOARD_INTERVAL; i++) {
        Thread.sleep(DEFAULT_KEYBOARD_INTERVAL);
        try {
            if (reader.ready()) {
                int value = reader.read();
                switch (value) {
                    case 'q':
                        return false;
                    case 'r':
                        reverseSort = !reverseSort;
                        break;
                    case '<':
                        if (sortIndex > 0) {
                            sortIndex--;
                        }
                        break;
                    case '>':
                        if (sortIndex < 5) {
                            sortIndex++;
                        }
                        break;
                }
            }
        } catch (IOException e) {

        }
    }

    return true;
}
 
Example 35
Project: rascal   File: ShellExec.java View source code Vote up 6 votes
public synchronized IString readFrom(IInteger processId) {
	if (!runningProcesses.containsKey(processId))
		throw RuntimeExceptionFactory.illegalArgument(processId, null, null);
	try {
		Process runningProcess = runningProcesses.get(processId);
		InputStreamReader isr = null;
		if (processInputStreams.containsKey(processId)) {
			isr = processInputStreams.get(processId);
		} else {
			isr = new InputStreamReader(runningProcess.getInputStream());
			processInputStreams.put(processId, isr);
		}
		StringBuffer line = new StringBuffer();
		while (isr.ready()) {
			line.append((char)isr.read());
		}
		return vf.string(line.toString());
	} catch (IOException e) {
		throw RuntimeExceptionFactory.javaException(e, null, null);
	}
}
 
Example 36
Project: dltk.ruby   File: RewriterTests.java View source code Vote up 6 votes
private String loadContent(String path) throws IOException {
	StringBuffer buffer = new StringBuffer();
	InputStream input = null;
	try {
		input = Activator.openResource(path);
		InputStreamReader reader = new InputStreamReader(input);

		char[] cbuf = new char[1024 * 16];
		while (reader.ready() == true) {
			int read = reader.read(cbuf);
			buffer.append(cbuf, 0, read);
		}
	}
	finally {
		if (input != null) {
			input.close();
		}
	}
	String content = buffer.toString();
	return content;
}
 
Example 37
Project: warlock2   File: StormFrontServerSettings.java View source code Vote up 6 votes
public static String readStream (InputStream stream)
{
	try {
		InputStreamReader reader = new InputStreamReader(stream);
		
		char chunk[] = new char[1024];
		StringBuffer buffer = new StringBuffer();
		
		while (reader.ready())
		{
			int read = reader.read(chunk);
			buffer.append(chunk, 0, read);
		}
		stream.close();
		
		return buffer.toString();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 38
Project: termsuite-core   File: TermSuiteCLIUtils.java View source code Vote up 6 votes
/**
 * Read the standard input as a string.
 * @return
 * @throws IOException
 */
public static String readIn(String encoding) throws IOException {
	if(in == null) {
		InputStreamReader reader = new InputStreamReader(System.in, encoding);
		List<Character> chars = new LinkedList<Character>();
		int c;
		while(reader.ready() && ((c = reader.read())!= -1)) 
			chars.add((char)c);
		
		char[] charAry = new char[chars.size()];
		for(int i=0; i<chars.size(); i++)
			charAry[i] = chars.get(i);
		in = new String(charAry);
	}
	return in;
}
 
Example 39
Project: SWTBot   File: ProjectCreator.java View source code Vote up 6 votes
private String read(InputStream is) {
	StringBuffer buffer = new StringBuffer();
	InputStreamReader in = null;
	try {
		in = new InputStreamReader(is, "utf-8");
		while (in.ready()) {
			buffer.append((char) in.read());
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	} finally {
		close(in);
	}
	return buffer.toString();
}
 
Example 40
Project: RankCapes   File: CapePack.java View source code Vote up 6 votes
/**
 * Parses the Zip file in memory.
 *
 * @param input the bytes of a valid zip file
 */
private void parsePack(byte[] input)
{
    try
    {
        ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(input));

        String metadata = "";

        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null)
        {
            String name = entry.getName();

            if (name.endsWith(".png"))
            {
                // remove file extension from the name.
                name = FilenameUtils.removeExtension(name);

                StaticCape cape = this.loadCape(name, zipInput);
                this.unprocessedCapes.put(name, cape);
            }
            else if (name.endsWith(".mcmeta"))
            {
                // parses the pack metadata.
                InputStreamReader streamReader = new InputStreamReader(zipInput);
                while (streamReader.ready())
                {
                    metadata += (char) streamReader.read();
                }
            }
        }
        if (!Strings.isNullOrEmpty(metadata))
        {
            this.parsePackMetadata(StringUtils.remove(metadata, (char) 65535));
        }
        else
        {
            RankCapesForge.log.warn("Cape Pack metadata is missing!");
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
Example 41
Project: GATECH   File: LL1Parser.java View source code Vote up 6 votes
/**
 * Parses the given input stream and returns the abstract syntax tree.
 * 
 * @param stream
 *            the stream to parse.
 * @return the resultant tree.
 */
public AST<String> parse(InputStream stream) throws IOException,
		ParseException {
	mStream = new InputStreamReader(stream);
	mBuffer = "";
	mStack = new Stack<Rule>();

	Rule endRule = new Rule(END);
	endRule.setTerminal(true);

	mStack.push(endRule);
	mStack.push(mRules.get(mStartRule));

	mResult = new AST<String>();

	mResult.setRoot(parse());

	char next = getNextCharacter();
	Rule r = mStack.pop();

	if (r.getName().equals(END) && Character.toString(next).equals(END))
		return mResult;
	else if (mStream.ready())
		throw new ParseException(
				"Finished parsing with content remaining in the file.",
				mLocation);
	else if (!mStack.empty())
		throw new ParseException("Input ended unexpectedly.", mLocation);
	else
		throw new ParseException("An unexpected error occured.",
				mLocation);
}
 
Example 42
Project: cdt   File: FileContentHelper.java View source code Vote up 6 votes
private static void skip(int count, InputStreamReader r) throws IOException {
	long skipped = 0;
	while(skipped >= 0 && count > 0 && r.ready()){
		skipped = r.skip(count);
		if(skipped > 0){
			count -= skipped;
		}
	}
}
 
Example 43
Project: cdt-tests-runner   File: FileContentHelper.java View source code Vote up 6 votes
private static void skip(int start, InputStreamReader r) throws IOException {
	long skipped = 0;
	while(skipped >= 0 && start > 0 && r.ready()){
		skipped = r.skip(start);
		if(skipped > 0){
			start -= skipped;
		}
	}
}
 
Example 44
Project: tt4j   File: Util.java View source code Vote up 6 votes
/**
 * For tests only.
 * 
 * @param aFile the file.
 * @param aEncoding the encoding.
 * @return the file content.
 * @throws IOException if an I/O error occurs.
 */
protected static
String readFile(
		final File aFile, 
		final String aEncoding)
throws IOException
{
	Reader reader = null;
	try {
    	StringBuilder sb = new StringBuilder();
    	CharBuffer buffer = CharBuffer.allocate(65535);
		reader = new InputStreamReader(new FileInputStream(aFile), aEncoding);
		while (reader.ready()) {
			reader.read(buffer);
			buffer.flip();
			sb.append(buffer.toString());
		}
		return sb.toString();
	}
	finally {
		close(reader);
	}
}
 
Example 45
Project: ManagedRuntimeInitiative   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 46
Project: openjdk   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 47
Project: domainmath-ide   File: UnicodeReader.java View source code Vote up 5 votes
/**
 * Read-ahead four bytes and check for BOM marks. Extra bytes are
 * unread back to the stream, only BOM bytes are skipped.
 *
 * @param defaultEncoding The encoding to use if no BOM was recognized.  If
 *        this value is <code>null</code>, then a system default is used.
 * @throws IOException If an error occurs when trying to read a BOM.
 */
protected void init(InputStream in, String defaultEncoding)
										throws IOException {

	PushbackInputStream tempIn = new PushbackInputStream(in, BOM_SIZE);

	byte bom[] = new byte[BOM_SIZE];
	int n, unread;
	n = tempIn.read(bom, 0, bom.length);

	if ((bom[0]==(byte)0x00) && (bom[1]==(byte)0x00) &&
			(bom[2]==(byte)0xFE) && (bom[3]==(byte)0xFF)) {
		encoding = "UTF-32BE";
		unread = n - 4;
	}

	else if (n==BOM_SIZE && // Last 2 bytes are 0; could be an empty UTF-16
			(bom[0]==(byte)0xFF) && (bom[1]==(byte)0xFE) &&
			(bom[2]==(byte)0x00) && (bom[3]==(byte)0x00)) {
		encoding = "UTF-32LE";
		unread = n - 4;
	}
	
	else if ((bom[0]==(byte)0xEF) &&
		(bom[1]==(byte)0xBB) &&
		(bom[2]==(byte)0xBF)) {
		encoding = "UTF-8";
		unread = n - 3;
	}

	else if ((bom[0]==(byte)0xFE) && (bom[1] == (byte)0xFF)) {
		encoding = "UTF-16BE";
		unread = n - 2;
	}

	else if ((bom[0]==(byte)0xFF) && (bom[1]== (byte)0xFE)) {
		encoding = "UTF-16LE";
		unread = n - 2;
	}

	else {
		// Unicode BOM mark not found, unread all bytes
		encoding = defaultEncoding;
		unread = n;
	}

	if (unread > 0)
		tempIn.unread(bom, (n - unread), unread);
	else if (unread < -1)
		tempIn.unread(bom, 0, 0);

	// Use given encoding
	if (encoding == null) {
		internalIn = new InputStreamReader(tempIn);
		encoding = internalIn.getEncoding(); // Get the default.
	}
	else {
		internalIn = new InputStreamReader(tempIn, encoding);
	}

}
 
Example 48
Project: openjdk8-jdk   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 49
Project: ESPlorer   File: UnicodeReader.java View source code Vote up 5 votes
/**
 * Read-ahead four bytes and check for BOM marks. Extra bytes are
 * unread back to the stream, only BOM bytes are skipped.
 *
 * @param defaultEncoding The encoding to use if no BOM was recognized.  If
 *        this value is <code>null</code>, then a system default is used.
 * @throws IOException If an error occurs when trying to read a BOM.
 */
protected void init(InputStream in, String defaultEncoding)
										throws IOException {

	PushbackInputStream tempIn = new PushbackInputStream(in, BOM_SIZE);

	byte bom[] = new byte[BOM_SIZE];
	int n, unread;
	n = tempIn.read(bom, 0, bom.length);

	if ((bom[0]==(byte)0x00) && (bom[1]==(byte)0x00) &&
			(bom[2]==(byte)0xFE) && (bom[3]==(byte)0xFF)) {
		encoding = "UTF-32BE";
		unread = n - 4;
	}

	else if (n==BOM_SIZE && // Last 2 bytes are 0; could be an empty UTF-16
			(bom[0]==(byte)0xFF) && (bom[1]==(byte)0xFE) &&
			(bom[2]==(byte)0x00) && (bom[3]==(byte)0x00)) {
		encoding = "UTF-32LE";
		unread = n - 4;
	}
	
	else if ((bom[0]==(byte)0xEF) &&
		(bom[1]==(byte)0xBB) &&
		(bom[2]==(byte)0xBF)) {
		encoding = "UTF-8";
		unread = n - 3;
	}

	else if ((bom[0]==(byte)0xFE) && (bom[1] == (byte)0xFF)) {
		encoding = "UTF-16BE";
		unread = n - 2;
	}

	else if ((bom[0]==(byte)0xFF) && (bom[1]== (byte)0xFE)) {
		encoding = "UTF-16LE";
		unread = n - 2;
	}

	else {
		// Unicode BOM mark not found, unread all bytes
		encoding = defaultEncoding;
		unread = n;
	}

	if (unread > 0)
		tempIn.unread(bom, (n - unread), unread);
	else if (unread < -1)
		tempIn.unread(bom, 0, 0);

	// Use given encoding
	if (encoding == null) {
		internalIn = new InputStreamReader(tempIn);
		encoding = internalIn.getEncoding(); // Get the default.
	}
	else {
		internalIn = new InputStreamReader(tempIn, encoding);
	}

}
 
Example 50
Project: Tank   File: UnicodeReader.java View source code Vote up 5 votes
/**
 * Read-ahead four bytes and check for BOM marks. Extra bytes are unread back to the stream, only BOM bytes are
 * skipped.
 * 
 * @param defaultEncoding
 *            The encoding to use if no BOM was recognized. If this value is <code>null</code>, then a system
 *            default is used.
 * @throws IOException
 *             If an error occurs when trying to read a BOM.
 */
protected void init(InputStream in, String defaultEncoding)
        throws IOException {

    PushbackInputStream tempIn = new PushbackInputStream(in, BOM_SIZE);

    byte bom[] = new byte[BOM_SIZE];
    int n, unread;
    n = tempIn.read(bom, 0, bom.length);

    if ((bom[0] == (byte) 0x00) && (bom[1] == (byte) 0x00) &&
            (bom[2] == (byte) 0xFE) && (bom[3] == (byte) 0xFF)) {
        encoding = "UTF-32BE";
        unread = n - 4;
    }

    else if (n == BOM_SIZE && // Last 2 bytes are 0; could be an empty UTF-16
            (bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE) &&
            (bom[2] == (byte) 0x00) && (bom[3] == (byte) 0x00)) {
        encoding = "UTF-32LE";
        unread = n - 4;
    }

    else if ((bom[0] == (byte) 0xEF) &&
            (bom[1] == (byte) 0xBB) &&
            (bom[2] == (byte) 0xBF)) {
        encoding = "UTF-8";
        unread = n - 3;
    }

    else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) {
        encoding = "UTF-16BE";
        unread = n - 2;
    }

    else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) {
        encoding = "UTF-16LE";
        unread = n - 2;
    }

    else {
        // Unicode BOM mark not found, unread all bytes
        encoding = defaultEncoding;
        unread = n;
    }

    if (unread > 0)
        tempIn.unread(bom, (n - unread), unread);
    else if (unread < -1)
        tempIn.unread(bom, 0, 0);

    // Use given encoding
    if (encoding == null) {
        internalIn = new InputStreamReader(tempIn);
        encoding = internalIn.getEncoding(); // Get the default.
    }
    else {
        internalIn = new InputStreamReader(tempIn, encoding);
    }

}
 
Example 51
Project: GdxStudio   File: UnicodeReader.java View source code Vote up 5 votes
/**
 * Read-ahead four bytes and check for BOM marks. Extra bytes are
 * unread back to the stream, only BOM bytes are skipped.
 *
 * @param defaultEncoding The encoding to use if no BOM was recognized.  If
 *        this value is <code>null</code>, then a system default is used.
 * @throws IOException If an error occurs when trying to read a BOM.
 */
protected void init(InputStream in, String defaultEncoding)
										throws IOException {

	PushbackInputStream tempIn = new PushbackInputStream(in, BOM_SIZE);

	byte bom[] = new byte[BOM_SIZE];
	int n, unread;
	n = tempIn.read(bom, 0, bom.length);

	if ((bom[0]==(byte)0x00) && (bom[1]==(byte)0x00) &&
			(bom[2]==(byte)0xFE) && (bom[3]==(byte)0xFF)) {
		encoding = "UTF-32BE";
		unread = n - 4;
	}

	else if (n==BOM_SIZE && // Last 2 bytes are 0; could be an empty UTF-16
			(bom[0]==(byte)0xFF) && (bom[1]==(byte)0xFE) &&
			(bom[2]==(byte)0x00) && (bom[3]==(byte)0x00)) {
		encoding = "UTF-32LE";
		unread = n - 4;
	}
	
	else if ((bom[0]==(byte)0xEF) &&
		(bom[1]==(byte)0xBB) &&
		(bom[2]==(byte)0xBF)) {
		encoding = "UTF-8";
		unread = n - 3;
	}

	else if ((bom[0]==(byte)0xFE) && (bom[1] == (byte)0xFF)) {
		encoding = "UTF-16BE";
		unread = n - 2;
	}

	else if ((bom[0]==(byte)0xFF) && (bom[1]== (byte)0xFE)) {
		encoding = "UTF-16LE";
		unread = n - 2;
	}

	else {
		// Unicode BOM mark not found, unread all bytes
		encoding = defaultEncoding;
		unread = n;
	}

	if (unread > 0)
		tempIn.unread(bom, (n - unread), unread);
	else if (unread < -1)
		tempIn.unread(bom, 0, 0);

	// Use given encoding
	if (encoding == null) {
		internalIn = new InputStreamReader(tempIn);
		encoding = internalIn.getEncoding(); // Get the default.
	}
	else {
		internalIn = new InputStreamReader(tempIn, encoding);
	}

}
 
Example 52
Project: platform_tools_motodev   File: TelnetFrameworkAndroid.java View source code Vote up 5 votes
/**
 *
 */
public String waitFor(String[] waitForArray) throws IOException
{
    InputStreamReader responseReader = null;
    StringBuffer answerFromRemoteHost = new StringBuffer();

    try
    {
        responseReader = new InputStreamReader(telnetClient.getInputStream());

        boolean found = false;

        do
        {
            char readChar = 0;
            long currentTime = System.currentTimeMillis();
            long timeoutTime = currentTime + timeout;

            while (readChar == 0)
            {
                if (responseReader == null)
                {
                    // responseReader can only be set to null if method
                    // releaseTelnetInputStreamReader()
                    // has been called, which should happen if host becomes
                    // unavailable.
                    throw new IOException(
                            "Telnet host is unavailable; stopped waiting for answer.");
                }

                if (responseReader.ready())
                {
                    readChar = (char) responseReader.read();
                }
                else
                {
                    try
                    {
                        Thread.sleep(50);
                    }
                    catch (InterruptedException e)
                    {
                        // Do nothing
                    }
                }

                currentTime = System.currentTimeMillis();

                if ((!responseReader.ready()) && (currentTime > timeoutTime))
                {
                    throw new IOException(
                            "A timeout has occured when trying to read the telnet stream");
                }
            }

            answerFromRemoteHost.append(readChar);

            for (String aWaitFor : waitForArray)
            {
                found = answerFromRemoteHost.toString().contains(aWaitFor);
            }

        }
        while (!found);
    }
    finally
    {
        if (responseReader != null)
        {
            responseReader.close();
        }
    }

    return answerFromRemoteHost.toString();
}