Example usage for java.io LineNumberReader close

List of usage examples for java.io LineNumberReader close

Introduction

In this page you can find the example usage for java.io LineNumberReader close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.eclipse.ice.client.widgets.moose.MOOSEFormEditor.java

/**
 * This private method is used to decide whether or not the given
 * ICEResource contains valid Postprocessor data to plot. Basically, for now
 * it naively checks that there is more than one line in the file, because
 * if there was 1 or less, then we would have no data or just the feature
 * line describing the data./*www  . java 2 s .  com*/
 * 
 * @param r
 * @return validData Whether or not there is valid data in the resource
 */
private boolean hasValidPostprocessorData(ICEResource r) {

    // Simply count the number of lines in the resource file
    try {
        LineNumberReader reader = new LineNumberReader(new FileReader(r.getPath().getPath()));
        int cnt = 0;
        String lineRead = "";
        while ((lineRead = reader.readLine()) != null) {
        }

        cnt = reader.getLineNumber();
        reader.close();

        if (cnt <= 1) {
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        logger.error(getClass().getName() + " Exception!", e);
        return false;
    }
}

From source file:org.openanzo.jdbc.opgen.ant.DDLTask.java

private void writeFile(Writer writer, String filename, String file, String outputFormat)
        throws FileNotFoundException, IOException {
    Reader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
    LineNumberReader lnr = new LineNumberReader(in);
    StringBuilder content = new StringBuilder();
    String line;/*  www  . ja va 2s .c  om*/
    while ((line = lnr.readLine()) != null) {
        line = StringUtils.trim(line);
        if (line.length() == 0 || line.startsWith("#"))
            continue;
        line = Pattern.compile("[\\s+]", Pattern.MULTILINE).matcher(line).replaceAll(" ");
        line = Pattern.compile(";+", Pattern.MULTILINE).matcher(line).replaceAll(";;");
        line = Pattern.compile("&sc", Pattern.MULTILINE).matcher(line).replaceAll(";");
        line = Pattern.compile("&plus", Pattern.MULTILINE).matcher(line).replaceAll("+");
        content.append(line);
        content.append(" ");
    }
    writer.write(content.toString());
    in.close();
    lnr.close();
}

From source file:edu.stanford.muse.index.Indexer.java

public static Set<String> readStreamAndInternStrings(Reader r) {
    Set<String> result = new LinkedHashSet<String>();
    try {/*from   w  w  w.j a  va 2 s .com*/
        LineNumberReader lnr = new LineNumberReader(r);
        while (true) {
            String word = lnr.readLine();
            if (word == null) {
                lnr.close();
                break;
            }
            word = word.trim();
            if (word.startsWith("#") || word.length() == 0)
                continue;
            word = IndexUtils.canonicalizeMultiWordTerm(word, false); // TOFIX: not really sure if stemming shd be off
            word = InternTable.intern(word);
            result.add(word);
        }
    } catch (IOException e) {
        log.warn("Exception reading reader " + r + ": " + e + Util.stackTrace(e));
    }

    return result;
}

From source file:edu.stanford.muse.index.Indexer.java

public static Set<String> readFileAndInternStrings(String file) {
    Set<String> result = new LinkedHashSet<String>();
    try {//from  w  w w  .  j a  v  a 2s . c o  m
        Reader r = null;
        if (file.toLowerCase().endsWith(".gz"))
            r = new InputStreamReader(new GZIPInputStream(new FileInputStream(file)));
        else
            r = new FileReader(file);

        LineNumberReader lnr = new LineNumberReader(r);
        while (true) {
            String word = lnr.readLine();
            if (word == null) {
                lnr.close();
                break;
            }
            word = word.trim();
            if (word.startsWith("#") || word.length() == 0)
                continue;
            word = IndexUtils.canonicalizeMultiWordTerm(word, false); // TOFIX: not really sure if stemming shd be on
            word = InternTable.intern(word);
            result.add(word);
        }
    } catch (IOException e) {
        log.warn("Exception reading file " + file + ": " + e + Util.stackTrace(e));
    }

    return result;
}

From source file:org.apache.cocoon.generation.TextGenerator.java

/**
 * Generate XML data.//from   www  .  ja v a2s. c o m
 *
 * @throws IOException
 * @throws ProcessingException
 * @throws SAXException
 */
public void generate() throws IOException, SAXException, ProcessingException {
    InputStreamReader in = null;

    try {
        final InputStream sis = this.inputSource.getInputStream();
        if (sis == null) {
            throw new ProcessingException("Source '" + this.inputSource.getURI() + "' not found");
        }

        if (encoding != null) {
            in = new InputStreamReader(sis, encoding);
        } else {
            in = new InputStreamReader(sis);
        }
    } catch (SourceException se) {
        throw new ProcessingException("Error during resolving of '" + this.source + "'.", se);
    }

    LocatorImpl locator = new LocatorImpl();

    locator.setSystemId(this.inputSource.getURI());
    locator.setLineNumber(1);
    locator.setColumnNumber(1);

    contentHandler.setDocumentLocator(locator);
    contentHandler.startDocument();
    contentHandler.startPrefixMapping("", URI);

    AttributesImpl atts = new AttributesImpl();
    if (localizable) {
        atts.addAttribute("", "source", "source", "CDATA", locator.getSystemId());
        atts.addAttribute("", "line", "line", "CDATA", String.valueOf(locator.getLineNumber()));
        atts.addAttribute("", "column", "column", "CDATA", String.valueOf(locator.getColumnNumber()));
    }

    contentHandler.startElement(URI, "text", "text", atts);

    LineNumberReader reader = new LineNumberReader(in);
    String line;
    String newline = null;

    while (true) {
        if (newline == null) {
            line = convertNonXmlChars(reader.readLine());
        } else {
            line = newline;
        }
        if (line == null) {
            break;
        }
        newline = convertNonXmlChars(reader.readLine());
        if (newline != null) {
            line += SystemUtils.LINE_SEPARATOR;
        }
        locator.setLineNumber(reader.getLineNumber());
        locator.setColumnNumber(1);
        contentHandler.characters(line.toCharArray(), 0, line.length());
        if (newline == null) {
            break;
        }
    }
    reader.close();
    contentHandler.endElement(URI, "text", "text");
    contentHandler.endPrefixMapping("");
    contentHandler.endDocument();
}

From source file:org.apache.cocoon.generation.TextGenerator2.java

/**
 * Generate XML data.//from  ww w  .  j  a va2 s  .  c o m
 *
 * @throws IOException
 * @throws ProcessingException
 * @throws SAXException
 */
public void generate() throws IOException, SAXException, ProcessingException {
    InputStreamReader in = null;
    try {
        final InputStream sis = this.inputSource.getInputStream();
        if (sis == null) {
            throw new ProcessingException("Source '" + this.inputSource.getURI() + "' not found");
        }
        if (encoding != null) {
            in = new InputStreamReader(sis, encoding);
        } else {
            in = new InputStreamReader(sis);
        }
    } catch (SourceException se) {
        throw new ProcessingException("Error during resolving of '" + this.source + "'.", se);
    }
    LocatorImpl locator = new LocatorImpl();
    locator.setSystemId(this.inputSource.getURI());
    locator.setLineNumber(1);
    locator.setColumnNumber(1);
    /* Do not pass the source URI to the contentHandler, assuming that that is the LexicalTransformer. It does not have to be.
      contentHandler.setDocumentLocator(locator);
    */
    contentHandler.startDocument();
    AttributesImpl atts = new AttributesImpl();
    if (localizable) {
        atts.addAttribute("", "source", "source", "CDATA", locator.getSystemId());
        atts.addAttribute("", "line", "line", "CDATA", String.valueOf(locator.getLineNumber()));
        atts.addAttribute("", "column", "column", "CDATA", String.valueOf(locator.getColumnNumber()));
    }
    String nsPrefix = this.element.contains(":") ? this.element.replaceFirst(":.+$", "") : "";
    String localName = this.element.replaceFirst("^.+:", "");
    if (this.namespace.length() > 1)
        contentHandler.startPrefixMapping(nsPrefix, this.namespace);
    contentHandler.startElement(this.namespace, localName, this.element, atts);
    LineNumberReader reader = new LineNumberReader(in);
    String line;
    String newline = null;
    while (true) {
        if (newline == null) {
            line = convertNonXmlChars(reader.readLine());
        } else {
            line = newline;
        }
        if (line == null) {
            break;
        }
        newline = convertNonXmlChars(reader.readLine());
        if (newline != null) {
            line += SystemUtils.LINE_SEPARATOR;
        }
        locator.setLineNumber(reader.getLineNumber());
        locator.setColumnNumber(1);
        contentHandler.characters(line.toCharArray(), 0, line.length());
        if (newline == null) {
            break;
        }
    }
    reader.close();
    contentHandler.endElement(this.namespace, localName, this.element);
    if (this.namespace.length() > 1)
        contentHandler.endPrefixMapping(nsPrefix);
    contentHandler.endDocument();
}

From source file:org.opencms.util.CmsRfsFileViewer.java

/**
 * Internally sets the member <code>m_windowPos</code> to the last available 
 * window of <code>m_windowSize</code> windows to let further calls to 
 * <code>{@link #readFilePortion()}</code> display the end of the file. <p> 
 * /*w ww .j  av a2s . com*/
 * This method is triggered when a new file is chosen 
 * (<code>{@link #setFilePath(String)}</code>) because the amount of lines changes. 
 * This method is also triggered when a different window size is chosen 
 * (<code>{@link #setWindowSize(int)}</code>) because the amount of lines to display change. 
 * 
 * @return the amount of lines in the file to view
 */
private int scrollToFileEnd() {

    int lines = 0;
    if (OpenCms.getRunLevel() < OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
        // no scrolling if system not yet fully initialized
    } else {
        LineNumberReader reader = null;
        // shift the window position to the end of the file: this is expensive but OK for ocs logfiles as they 
        // are ltd. to 2 MB
        try {
            reader = new LineNumberReader(
                    new BufferedReader(new InputStreamReader(new FileInputStream(m_filePath))));
            while (reader.readLine() != null) {
                lines++;
            }
            reader.close();
            // if 11.75 windows are available, we don't want to end on window nr. 10 
            int availWindows = (int) Math.ceil((double) lines / (double) m_windowSize);
            // we start with window 0
            m_windowPos = availWindows - 1;
        } catch (IOException ioex) {
            LOG.error("Unable to scroll file " + m_filePath + " to end. Ensure that it exists. ");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Throwable f) {
                    LOG.info("Unable to close reader of file " + m_filePath, f);
                }
            }
        }
    }
    return lines;
}

From source file:com.penguineering.cleanuri.sites.reichelt.ReicheltExtractor.java

@Override
public Map<Metakey, String> extractMetadata(URI uri) throws ExtractorException {
    if (uri == null)
        throw new NullPointerException("URI argument must not be null!");

    URL url;//from ww  w.j  av a 2s . co  m
    try {
        url = uri.toURL();
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("The provided URI is not a URL!");
    }

    Map<Metakey, String> meta = new HashMap<Metakey, String>();

    try {
        final URLConnection con = url.openConnection();

        LineNumberReader reader = null;
        try {
            reader = new LineNumberReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.contains("<h2>"))
                    continue;

                // h2
                int h2_idx = line.indexOf("h2");
                // Doppelpunkte
                int col_idx = line.indexOf("<span> :: <span");
                final String art_id = line.substring(h2_idx + 3, col_idx);
                meta.put(Metakey.ID, html2oUTF8(art_id).trim());

                int span_idx = line.indexOf("</span>");
                final String art_name = line.substring(col_idx + 32, span_idx);
                meta.put(Metakey.NAME, html2oUTF8(art_name).trim());

                break;
            }

            return meta;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (IOException e) {
        throw new ExtractorException("I/O exception during extraction: " + e.getMessage(), e, uri);
    }

}

From source file:org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.java

/**
 * Read a script from the given resource and build a String containing the lines.
 * @param resource the resource to be read
 * @return {@code String} containing the script lines
 * @throws IOException in case of I/O errors
 *//*from  w w w.j  av  a2 s .co  m*/
private String readScript(EncodedResource resource) throws IOException {
    LineNumberReader lnr = new LineNumberReader(resource.getReader());
    try {
        String currentStatement = lnr.readLine();
        StringBuilder scriptBuilder = new StringBuilder();
        while (currentStatement != null) {
            if (StringUtils.hasText(currentStatement)
                    && (this.commentPrefix != null && !currentStatement.startsWith(this.commentPrefix))) {
                if (scriptBuilder.length() > 0) {
                    scriptBuilder.append('\n');
                }
                scriptBuilder.append(currentStatement);
            }
            currentStatement = lnr.readLine();
        }
        maybeAddSeparatorToScript(scriptBuilder);
        return scriptBuilder.toString();
    } finally {
        lnr.close();
    }
}

From source file:org.kuali.test.runner.execution.TestExecutionMonitor.java

private File getMergedPerformanceDataFile() {
    File retval = null;//  ww w  .j  a v a  2 s. c  o  m
    PrintWriter pw = null;
    try {
        boolean headerWritten = false;
        for (TestExecutionContext tec : testExecutionList) {
            File f = tec.getPerformanceDataFile();
            if (f != null) {
                if (pw == null) {
                    int pos = f.getPath().lastIndexOf("_");
                    pw = new PrintWriter(retval = new File(f.getPath().substring(0, pos) + ".csv"));
                }

                LineNumberReader lnr = null;
                try {
                    lnr = new LineNumberReader(new FileReader(f));

                    if (headerWritten) {
                        lnr.readLine();
                    }

                    String line = null;

                    while ((line = lnr.readLine()) != null) {
                        pw.println(line);
                    }

                    headerWritten = true;
                }

                catch (Exception ex) {
                    LOG.error(ex.toString(), ex);
                }

                finally {
                    if (lnr != null) {
                        try {
                            lnr.close();
                            FileUtils.deleteQuietly(f);
                        }

                        catch (Exception ex) {
                        }
                        ;
                    }
                }
            }
        }
    }

    catch (Exception ex) {
        LOG.error(ex.toString(), ex);
        retval = null;
    }

    finally {
        if (pw != null) {
            pw.close();
        }
    }

    return retval;
}