Example usage for java.io InputStreamReader read

List of usage examples for java.io InputStreamReader read

Introduction

In this page you can find the example usage for java.io InputStreamReader read.

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * Returns the root node uuid.//from   w  w  w.java 2  s . c om
 * @param fs
 * @return
 * @throws RepositoryException
 */
protected NodeId loadRootNodeId(FileSystem fs) throws RepositoryException {
    FileSystemResource uuidFile = new FileSystemResource(fs, "rootUUID");
    try {
        if (uuidFile.exists()) {
            try {
                // load uuid of the repository's root node
                InputStream in = uuidFile.getInputStream();
                /*
                                   // uuid is stored in binary format (16 bytes)
                                   byte[] bytes = new byte[16];
                                   try {
                                       in.read(bytes);
                                   } finally {
                                       try {
                   in.close();
                                       } catch (IOException ioe) {
                   // ignore
                                       }
                                   }
                                   rootNodeUUID = new UUID(bytes).toString();            // uuid is stored in binary format (16 bytes)
                */
                // uuid is stored in text format (36 characters) for better readability
                char[] chars = new char[36];
                InputStreamReader reader = new InputStreamReader(in);
                try {
                    reader.read(chars);
                } finally {
                    IOUtils.closeQuietly(reader);
                }
                return NodeId.valueOf(new String(chars));
            } catch (Exception e) {
                String msg = "failed to load persisted repository state";
                log.debug(msg);
                throw new RepositoryException(msg, e);
            }
        } else {
            // create new uuid
            /*
                            UUID rootUUID = UUID.randomUUID();     // version 4 uuid
                            rootNodeUUID = rootUUID.toString();
            */
            /**
             * use hard-coded uuid for root node rather than generating
             * a different uuid per repository instance; using a
             * hard-coded uuid makes it easier to copy/move entire
             * workspaces from one repository instance to another.
             */
            try {
                // persist uuid of the repository's root node
                OutputStream out = uuidFile.getOutputStream();
                /*
                                    // store uuid in binary format
                                    try {
                out.write(rootUUID.getBytes());
                                    } finally {
                try {
                    out.close();
                } catch (IOException ioe) {
                    // ignore
                }
                                    }
                */
                // store uuid in text format for better readability
                OutputStreamWriter writer = new OutputStreamWriter(out);
                try {
                    writer.write(ROOT_NODE_ID.toString());
                } finally {
                    IOUtils.closeQuietly(writer);
                }
                return ROOT_NODE_ID;
            } catch (Exception e) {
                String msg = "failed to persist repository state";
                log.debug(msg);
                throw new RepositoryException(msg, e);
            }
        }
    } catch (FileSystemException fse) {
        String msg = "failed to access repository state";
        log.debug(msg);
        throw new RepositoryException(msg, fse);
    }
}

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * Returns the root node uuid.//from   w  w w .j  a  v  a  2s.  co  m
 * @param fs
 * @return
 * @throws RepositoryException
 */
protected NodeId loadRootNodeId(FileSystem fs) throws RepositoryException {
    FileSystemResource uuidFile = new FileSystemResource(fs, "rootUUID");
    try {
        if (uuidFile.exists()) {
            try {
                // load uuid of the repository's root node
                InputStream in = uuidFile.getInputStream();
                /*
                                   // uuid is stored in binary format (16 bytes)
                                   byte[] bytes = new byte[16];
                                   try {
                                       in.read(bytes);
                                   } finally {
                                       try {
                   in.close();
                                       } catch (IOException ioe) {
                   // ignore
                                       }
                                   }
                                   rootNodeUUID = new UUID(bytes).toString();            // uuid is stored in binary format (16 bytes)
                */
                // uuid is stored in text format (36 characters) for better readability
                char[] chars = new char[36];
                InputStreamReader reader = new InputStreamReader(in);
                try {
                    reader.read(chars);
                } finally {
                    try {
                        reader.close();
                    } catch (IOException ioe) {
                        // ignore
                    }
                }
                return NodeId.valueOf(new String(chars));
            } catch (Exception e) {
                String msg = "failed to load persisted repository state";
                log.debug(msg);
                throw new RepositoryException(msg, e);
            }
        } else {
            // create new uuid
            /*
                            UUID rootUUID = UUID.randomUUID();     // version 4 uuid
                            rootNodeUUID = rootUUID.toString();
            */
            /**
             * use hard-coded uuid for root node rather than generating
             * a different uuid per repository instance; using a
             * hard-coded uuid makes it easier to copy/move entire
             * workspaces from one repository instance to another.
             */
            try {
                // persist uuid of the repository's root node
                OutputStream out = uuidFile.getOutputStream();
                /*
                                    // store uuid in binary format
                                    try {
                out.write(rootUUID.getBytes());
                                    } finally {
                try {
                    out.close();
                } catch (IOException ioe) {
                    // ignore
                }
                                    }
                */
                // store uuid in text format for better readability
                OutputStreamWriter writer = new OutputStreamWriter(out);
                try {
                    writer.write(ROOT_NODE_ID.toString());
                } finally {
                    try {
                        writer.close();
                    } catch (IOException ioe) {
                        // ignore
                    }
                }
                return ROOT_NODE_ID;
            } catch (Exception e) {
                String msg = "failed to persist repository state";
                log.debug(msg);
                throw new RepositoryException(msg, e);
            }
        }
    } catch (FileSystemException fse) {
        String msg = "failed to access repository state";
        log.debug(msg);
        throw new RepositoryException(msg, fse);
    }
}

From source file:org.smilec.smile.student.CourseList.java

private void readHTMLfromResouceFile(String fileName) {
    InputStream is;/*  w  w w.  ja v a 2 s  . c  o  m*/
    try {
        is = getAssets().open(fileName);
    } catch (IOException e) {
        return;
    }

    InputStreamReader isr = new InputStreamReader(is);
    StringBuffer builder = new StringBuffer();
    char buffer[] = new char[1024];

    try {
        int chars;

        while ((chars = isr.read(buffer)) >= 0) {
            builder.append(buffer, 0, chars);
        }
    } catch (IOException e) {
        return;
    }

    String htmlstring = builder.toString();
    curwebview.loadDataWithBaseURL("file:///android_asset/", htmlstring, "text/html", "utf-8", "");
}

From source file:au.org.ala.layers.dao.ObjectDAOImpl.java

@Override
public void streamObjectsGeometryById(OutputStream os, String id, String geomtype) throws IOException {
    logger.info("Getting object info for id = " + id + " and geometry as " + geomtype);
    String sql = "";
    if ("kml".equals(geomtype)) {
        sql = "SELECT ST_AsKml(the_geom) as geometry, name, \"desc\" as description  FROM objects WHERE pid=?;";
    } else if ("wkt".equals(geomtype)) {
        sql = "SELECT ST_AsText(the_geom) as geometry FROM objects WHERE pid=?;";
    } else if ("geojson".equals(geomtype)) {
        sql = "SELECT ST_AsGeoJSON(the_geom) as geometry FROM objects WHERE pid=?;";
    } else if ("shp".equals(geomtype)) {
        sql = "SELECT ST_AsText(the_geom) as geometry, name, \"desc\" as description FROM objects WHERE pid=?;";
    }/* ww w  .j  a v  a 2 s.  c  om*/

    List<Objects> l = jdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper.newInstance(Objects.class),
            id);

    if (l.size() > 0) {
        if ("shp".equals(geomtype)) {
            String wkt = l.get(0).getGeometry();
            File zippedShapeFile = SpatialConversionUtils.buildZippedShapeFile(wkt, id, l.get(0).getName(),
                    l.get(0).getDescription());
            FileUtils.copyFile(zippedShapeFile, os);
        } else if ("kml".equals(geomtype)) {
            os.write(KML_HEADER.replace("<name></name>", "<name><![CDATA[" + l.get(0).getName() + "]]></name>")
                    .replace("<description></description>",
                            "<description><![CDATA[" + l.get(0).getDescription() + "]]></description>")
                    .getBytes());

            os.write(l.get(0).getGeometry().getBytes());
            os.write(KML_FOOTER.getBytes());
        } else {
            os.write(l.get(0).getGeometry().getBytes());
        }

    } else {
        // get grid classes
        if (id.length() > 0) {
            // grid class pids are, 'layerPid:gridClassNumber'
            try {
                String[] s = id.split(":");
                if (s.length >= 2) {
                    int n = Integer.parseInt(s[1]);
                    IntersectionFile f = layerIntersectDao.getConfig().getIntersectionFile(s[0]);
                    if (f != null && f.getClasses() != null) {
                        GridClass gc = f.getClasses().get(n);
                        if (gc != null && ("kml".equals(geomtype) || "wkt".equals(geomtype)
                                || "geojson".equals(geomtype) || "shp".equals(geomtype))) {
                            // TODO: enable for type 'a' after
                            // implementation of fields table defaultLayer
                            // field

                            File file = new File(
                                    f.getFilePath() + File.separator + s[1] + "." + geomtype + ".zip");
                            if ((f.getType().equals("a") || s.length == 2) && file.exists()) {
                                ZipInputStream zis = null;
                                try {
                                    zis = new ZipInputStream(new FileInputStream(file));

                                    zis.getNextEntry();
                                    byte[] buffer = new byte[1024];
                                    int size;
                                    while ((size = zis.read(buffer)) > 0) {
                                        os.write(buffer, 0, size);
                                    }
                                } catch (Exception e) {
                                    logger.error(e.getMessage(), e);
                                } finally {
                                    if (zis != null) {
                                        try {
                                            zis.close();
                                        } catch (Exception e) {
                                            logger.error(e.getMessage(), e);
                                        }
                                    }
                                }
                            } else { // polygon
                                BufferedInputStream bis = null;
                                InputStreamReader isr = null;
                                try {
                                    String[] cells = null;

                                    HashMap<String, Object> map = s.length == 2 ? null
                                            : getGridIndexEntry(f.getFilePath() + File.separator + s[1], s[2]);

                                    String wkt = null;
                                    if (map != null) {
                                        cells = new String[] { s[2], String.valueOf(map.get("charoffset")) };
                                        if (cells != null) {
                                            // get polygon wkt string
                                            File file2 = new File(
                                                    f.getFilePath() + File.separator + s[1] + ".wkt");
                                            bis = new BufferedInputStream(new FileInputStream(file2));
                                            isr = new InputStreamReader(bis);
                                            isr.skip(Long.parseLong(cells[1]));
                                            char[] buffer = new char[1024];
                                            int size;
                                            StringBuilder sb = new StringBuilder();
                                            sb.append("POLYGON");
                                            int end = -1;
                                            while (end < 0 && (size = isr.read(buffer)) > 0) {
                                                sb.append(buffer, 0, size);
                                                end = sb.toString().indexOf("))");
                                            }
                                            end += 2;

                                            wkt = sb.toString().substring(0, end);
                                        }
                                    } else {
                                        wkt = gc.getBbox();
                                    }

                                    if (geomtype.equals("wkt")) {
                                        os.write(wkt.getBytes());
                                    } else {
                                        WKTReader r = new WKTReader();
                                        Geometry g = r.read(wkt);

                                        if (geomtype.equals("kml")) {
                                            os.write(KML_HEADER.getBytes());
                                            Encoder encoder = new Encoder(new KMLConfiguration());
                                            encoder.setIndenting(true);
                                            encoder.encode(g, KML.Geometry, os);
                                            os.write(KML_FOOTER.getBytes());
                                        } else if (geomtype.equals("geojson")) {
                                            FeatureJSON fjson = new FeatureJSON();
                                            final SimpleFeatureType TYPE = DataUtilities.createType("class",
                                                    "the_geom:MultiPolygon,name:String");
                                            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                                                    TYPE);
                                            featureBuilder.add(g);
                                            featureBuilder.add(gc.getName());
                                            fjson.writeFeature(featureBuilder.buildFeature(null), os);
                                        } else if (geomtype == "shp") {
                                            File zippedShapeFile = SpatialConversionUtils
                                                    .buildZippedShapeFile(wkt, id, gc.getName(), null);
                                            FileUtils.copyFile(zippedShapeFile, os);
                                        }
                                    }
                                } catch (Exception e) {
                                    logger.error(e.getMessage(), e);
                                } finally {
                                    if (bis != null) {
                                        try {
                                            bis.close();
                                        } catch (Exception e) {
                                            logger.error(e.getMessage(), e);
                                        }
                                    }
                                    if (isr != null) {
                                        try {
                                            isr.close();
                                        } catch (Exception e) {
                                            logger.error(e.getMessage(), e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

From source file:fi.hoski.remote.ui.Admin.java

private JSONObject getRating(String ratingSystem, String nat, int sailNo, String boatClass)
        throws IOException, JSONException {
    try {/*www  .j  a va2s  . co  m*/
        String path = "/race?RatingSystem=" + ratingSystem + "&Nat=" + nat + "&SailNo=" + sailNo + "&Class="
                + boatClass;
        URL url = new URL("http", server, path.replace(' ', '+'));
        InputStream is = url.openStream();
        InputStreamReader isr = new InputStreamReader(is, "ASCII");
        StringBuilder sb = new StringBuilder();
        char[] cb = new char[256];
        int rc = isr.read(cb);
        while (rc != -1) {
            sb.append(cb, 0, rc);
            rc = isr.read(cb);
        }
        return new JSONObject(sb.toString());
    } catch (MalformedURLException ex) {
        Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.izforge.izpack.compiler.CompilerConfig.java

/**
 * Adds the resources./*from w  w w .j  a v  a  2s  .  c  o m*/
 *
 * @param data The XML data.
 * @throws CompilerException Description of the Exception
 */
protected void addResources(IXMLElement data) throws CompilerException {
    notifyCompilerListener("addResources", CompilerListener.BEGIN, data);
    IXMLElement root = data.getFirstChildNamed("resources");
    if (root == null) {
        return;
    }

    // We process each res markup
    for (IXMLElement resNode : root.getChildrenNamed("res")) {
        String id = xmlCompilerHelper.requireAttribute(resNode, "id");
        String src = xmlCompilerHelper.requireAttribute(resNode, "src");
        // the parse attribute causes substitution to occur
        boolean substitute = xmlCompilerHelper.validateYesNoAttribute(resNode, "parse", NO);
        // the parsexml attribute causes the xml document to be parsed
        boolean parsexml = xmlCompilerHelper.validateYesNoAttribute(resNode, "parsexml", NO);

        String encoding = resNode.getAttribute("encoding");
        if (encoding == null) {
            encoding = "";
        }

        // basedir is not prepended if src is already an absolute path
        URL originalUrl = resourceFinder.findProjectResource(src, "Resource", resNode);
        URL url = originalUrl;

        InputStream is = null;
        OutputStream os = null;
        try {
            if (parsexml || (!"".equals(encoding)) || (substitute && !packager.getVariables().isEmpty())) {
                // make the substitutions into a temp file
                File parsedFile = FileUtils.createTempFile("izpp", null);
                parsedFile.deleteOnExit();
                FileOutputStream outFile = new FileOutputStream(parsedFile);
                os = new BufferedOutputStream(outFile);
                // and specify the substituted file to be added to the
                // packager
                url = parsedFile.toURI().toURL();
            }

            if (!"".equals(encoding)) {
                File recodedFile = FileUtils.createTempFile("izenc", null);
                recodedFile.deleteOnExit();

                InputStreamReader reader = new InputStreamReader(originalUrl.openStream(), encoding);
                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(recodedFile), "UTF-8");

                char[] buffer = new char[1024];
                int read;
                while ((read = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, read);
                }
                reader.close();
                writer.close();
                if (parsexml) {
                    originalUrl = recodedFile.toURI().toURL();
                } else {
                    url = recodedFile.toURI().toURL();
                }
            }

            if (parsexml) {
                IXMLParser parser = new XMLParser();
                // this constructor will open the specified url (this is
                // why the InputStream is not handled in a similar manner
                // to the OutputStream)

                IXMLElement xml = parser.parse(originalUrl);
                IXMLWriter writer = new XMLWriter();
                if (substitute && !packager.getVariables().isEmpty()) {
                    // if we are also performing substitutions on the file
                    // then create an in-memory copy to pass to the
                    // substitutor
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    writer.setOutput(baos);
                    is = new ByteArrayInputStream(baos.toByteArray());
                } else {
                    // otherwise write direct to the temp file
                    writer.setOutput(os);
                }
                writer.write(xml);
            }

            // substitute variable values in the resource if parsed
            if (substitute) {
                if (packager.getVariables().isEmpty()) {
                    // reset url to original.
                    url = originalUrl;
                    assertionHelper.parseWarn(resNode,
                            "No variables defined. " + url.getPath() + " not parsed.");
                } else {
                    SubstitutionType type = SubstitutionType.lookup(resNode.getAttribute("type"));

                    // if the xml parser did not open the url
                    // ('parsexml' was not enabled)
                    if (null == is) {
                        is = new BufferedInputStream(originalUrl.openStream());
                    }
                    // VariableSubstitutor vs = new
                    // VariableSubstitutorImpl(compiler.getVariables());
                    variableSubstitutor.substitute(is, os, type, "UTF-8");
                }
            }

        } catch (Exception e) {
            assertionHelper.parseError(resNode, e.getMessage(), e);
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    // ignore as there is nothing we can realistically do
                    // so lets at least try to close the input stream
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    // ignore as there is nothing we can realistically do
                }
            }
        }

        packager.addResource(id, url);

        // remembering references to all added packsLang.xml files
        if (id.startsWith("packsLang.xml")) {
            List<URL> packsLangURLs;
            if (packsLangUrlMap.containsKey(id)) {
                packsLangURLs = packsLangUrlMap.get(id);
            } else {
                packsLangURLs = new ArrayList<URL>();
                packsLangUrlMap.put(id, packsLangURLs);
            }
            packsLangURLs.add(url);
        } else if (id.startsWith(UserInputPanel.SPEC_FILE_NAME)) {
            // Check user input panel definitions
            IXMLElement xml = new XMLParser().parse(url);
            for (IXMLElement userPanelDef : xml.getChildrenNamed(UserInputPanel.NODE_ID)) {
                String userPanelId = xmlCompilerHelper.requireAttribute(userPanelDef, "id");
                if (userInputPanelIds == null) {
                    userInputPanelIds = new HashSet<String>();
                }
                if (!userInputPanelIds.add(userPanelId)) {
                    assertionHelper.parseError(xml, "Resource " + UserInputPanel.SPEC_FILE_NAME
                            + ": Duplicate user input panel identifier '" + userPanelId + "'");
                }
            }
        }
    }
    notifyCompilerListener("addResources", CompilerListener.END, data);
}

From source file:tufts.vue.URLResource.java

private Properties scrapeHTMLmetaData(URLConnection connection, int maxSearchBytes) throws java.io.IOException {
    Properties metaData = new Properties();

    InputStream byteStream = connection.getInputStream();

    if (DEBUG.DND && DEBUG.META) {
        System.err.println("Getting headers from " + connection);
        System.err.println("Headers: " + connection.getHeaderFields());
    }/*from   ww  w .  j  av a 2 s .c o m*/

    // note: be sure to call getContentType and don't rely on getting it from the HeaderFields map,
    // as sometimes it's set by the OS for a file:/// URL when there are no header fields (no http server)
    // (actually, this is set by java via a mime type table based on file extension, or a guess based on the stream)
    if (DEBUG.DND)
        System.err.println("*** getting contentType & encoding...");
    final String contentType = connection.getContentType();
    final String contentEncoding = connection.getContentEncoding();
    final int contentLength = connection.getContentLength();

    if (DEBUG.DND)
        System.err.println("*** contentType [" + contentType + "]");
    if (DEBUG.DND)
        System.err.println("*** contentEncoding [" + contentEncoding + "]");
    if (DEBUG.DND)
        System.err.println("*** contentLength [" + contentLength + "]");

    setProperty("url.contentType", contentType);
    setProperty("url.contentEncoding", contentEncoding);
    if (contentLength >= 0)
        setProperty("url.contentLength", contentLength);

    //if (contentType.toLowerCase().startsWith("text/html") == false) {
    if (!isHTML()) { // we only currently handle HTML
        if (DEBUG.Enabled)
            System.err.println("*** contentType [" + contentType + "] not HTML; skipping title extraction");
        return metaData;
    }

    if (DEBUG.DND)
        System.err.println("*** scanning for HTML meta-data...");

    try {
        final BufferedInputStream bufStream = new BufferedInputStream(byteStream, maxSearchBytes);
        bufStream.mark(maxSearchBytes);

        final byte[] byteBuffer = new byte[maxSearchBytes];
        int bytesRead = 0;
        int len = 0;
        // BufferedInputStream still won't read thru a block, so we need to allow
        // a few reads here to get thru a couple of blocks, so we can get up to
        // our maxbytes (e.g., a common return chunk count is 1448 bytes, presumably related to the MTU)
        do {
            int max = maxSearchBytes - bytesRead;
            len = bufStream.read(byteBuffer, bytesRead, max);
            System.out.println("*** read " + len);
            if (len > 0)
                bytesRead += len;
            else if (len < 0)
                break;
        } while (len > 0 && bytesRead < maxSearchBytes);
        if (DEBUG.DND)
            System.out.println("*** Got total chars: " + bytesRead);
        String html = new String(byteBuffer, 0, bytesRead);
        if (DEBUG.DND && DEBUG.META)
            System.out.println("*** HTML-STRING[" + html + "]");

        // first, look for a content encoding, so we can search for and get the title
        // on a properly encoded character stream

        String charset = null;

        Matcher cm = Content_Charset_Regex.matcher(html);
        if (cm.lookingAt()) {
            charset = cm.group(1);
            if (DEBUG.DND)
                System.err.println("*** found HTML specified charset [" + charset + "]");
            setProperty("charset", charset);
        }

        if (charset == null && contentEncoding != null) {
            if (DEBUG.DND || true)
                System.err.println("*** no charset found: using contentEncoding charset " + contentEncoding);
            charset = contentEncoding;
        }

        final String decodedHTML;

        if (charset != null) {
            bufStream.reset();
            InputStreamReader decodedStream = new InputStreamReader(bufStream, charset);
            //InputStreamReader decodedStream = new InputStreamReader(new ByteArrayInputStream(byteBuffer), charset);
            if (true || DEBUG.DND)
                System.out.println("*** decoding bytes into characters with official encoding "
                        + decodedStream.getEncoding());
            setProperty("contentEncoding", decodedStream.getEncoding());
            char[] decoded = new char[bytesRead];
            int decodedChars = decodedStream.read(decoded);
            decodedStream.close();
            if (true || DEBUG.DND)
                System.err.println("*** " + decodedChars + " characters decoded using " + charset);
            decodedHTML = new String(decoded, 0, decodedChars);
        } else
            decodedHTML = html; // we'll just have to go with the default platform charset...

        // these needed to be left open till the decodedStream was done, which
        // although it should never need to read beyond what's already buffered,
        // some internal java code has checks that make sure the underlying stream
        // isn't closed, even it it isn't used.
        byteStream.close();
        bufStream.close();

        Matcher m = HTML_Title_Regex.matcher(decodedHTML);
        if (m.lookingAt()) {
            String title = m.group(1);
            if (true || DEBUG.DND)
                System.err.println("*** found title [" + title + "]");
            metaData.put("title", title.trim());
        }

    } catch (Throwable e) {
        System.err.println("scrapeHTMLmetaData: " + e);
        if (DEBUG.DND)
            e.printStackTrace();
    }

    if (DEBUG.DND || DEBUG.Enabled)
        System.err.println("*** scrapeHTMLmetaData returning [" + metaData + "]");
    return metaData;
}

From source file:edu.mit.viral.shen.DroidFish.java

private final Dialog networkEngineDialog() {
    String[] fileNames = findFilesInDirectory(engineDir, new FileNameFilter() {
        @Override/*w w w  .  j  a va  2 s .c o  m*/
        public boolean accept(String filename) {
            if (internalEngine(filename))
                return false;
            try {
                InputStream inStream = new FileInputStream(filename);
                InputStreamReader inFile = new InputStreamReader(inStream);
                char[] buf = new char[4];
                boolean ret = (inFile.read(buf) == 4) && "NETE".equals(new String(buf));
                inFile.close();
                return ret;
            } catch (IOException e) {
                return false;
            }
        }
    });
    final int numFiles = fileNames.length;
    final int numItems = numFiles + 1;
    final String[] items = new String[numItems];
    final String[] ids = new String[numItems];
    int idx = 0;
    String sep = File.separator;
    String base = Environment.getExternalStorageDirectory() + sep + engineDir + sep;
    for (int i = 0; i < numFiles; i++) {
        ids[idx] = base + fileNames[i];
        items[idx] = fileNames[i];
        idx++;
    }
    ids[idx] = "";
    items[idx] = getString(R.string.new_engine);
    idx++;
    String currEngine = ctrl.getEngine();
    int defaultItem = 0;
    for (int i = 0; i < numItems; i++)
        if (ids[i].equals(currEngine)) {
            defaultItem = i;
            break;
        }
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.configure_network_engine);
    builder.setSingleChoiceItems(items, defaultItem, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            if ((item < 0) || (item >= numItems))
                return;
            dialog.dismiss();
            if (item == numItems - 1) {
                showDialog(NEW_NETWORK_ENGINE_DIALOG);
            } else {
                networkEngineToConfig = ids[item];
                removeDialog(NETWORK_ENGINE_CONFIG_DIALOG);
                showDialog(NETWORK_ENGINE_CONFIG_DIALOG);
            }
        }
    });
    builder.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            removeDialog(MANAGE_ENGINES_DIALOG);
            showDialog(MANAGE_ENGINES_DIALOG);
        }
    });
    AlertDialog alert = builder.create();
    return alert;
}

From source file:com.cohort.util.String2.java

/**
 * This reads the bytes of the file with the specified charset.
 * This does not alter the characters (e.g., the line endings).
 * /*from   w ww . j  a  v a2s .c om*/
 * <P>This method is generally appropriate for small and medium-sized
 * files. For very large files or files that need additional processing,
 * it may be better to write a custom method to
 * read the file line-by-line, processing as it goes.
 *
 * @param fileName is the (usually canonical) path (dir+name) for the file
 * @param charset e.g., ISO-8859-1, UTF-8, or "" or null for the default (ISO-8859-1)
 * @return a String with the decoded contents of the file.
 * @throws Exception if trouble
 */
public static String directReadFromFile(String fileName, String charset) throws Exception {

    //declare the BufferedReader variable
    //declare the results variable: String results[] = {"", ""}; 
    //BufferedReader and results are declared outside try/catch so 
    //that they can be accessed from within either try/catch block.
    long time = System.currentTimeMillis();
    FileInputStream fis = new FileInputStream(fileName);
    InputStreamReader isr = new InputStreamReader(fis,
            charset == null || charset.length() == 0 ? ISO_8859_1 : charset);
    StringBuilder sb = new StringBuilder(8192);

    //get the text from the file
    try {
        char buffer[] = new char[8192];
        int nRead;
        while ((nRead = isr.read(buffer)) >= 0) //-1 = end-of-file
            sb.append(buffer, 0, nRead);
    } finally {
        try {
            isr.close();
        } catch (Exception e) {
        }
    }
    return sb.toString();
}