Example usage for java.io LineNumberReader LineNumberReader

List of usage examples for java.io LineNumberReader LineNumberReader

Introduction

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

Prototype

public LineNumberReader(Reader in) 

Source Link

Document

Create a new line-numbering reader, using the default input-buffer size.

Usage

From source file:edu.stanford.muse.util.Util.java

public static String readFile(String file) throws IOException {
    StringBuilder sb = new StringBuilder();
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
    while (true) {
        String line = lnr.readLine();
        if (line == null)
            break;
        line = line.trim();//www . j av  a2 s  .  c  om
        sb.append(line);
        sb.append("\n");
    }
    lnr.close();
    return sb.toString();
}

From source file:org.wildfly.core.test.standalone.mgmt.api.core.ResponseAttachmentTestCase.java

private void readLogStream(InputStream stream) throws IOException {
    LineNumberReader reader = new LineNumberReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
    String read;/*from ww  w .  j  av  a 2s  . com*/
    String lastRead = null;
    boolean readMessage = false;
    String expected = LogStreamExtension.getLogMessage(logMessageContent);
    while ((read = reader.readLine()) != null) {
        readMessage = readMessage || read.contains(expected);
        lastRead = read;
    }

    Assert.assertTrue("Did not see " + expected + " -- last read was " + lastRead, readMessage);

}

From source file:StockForecast.Stock.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    // TODO add your handling code here:
    try {//from w  ww  . j  a v a 2s  .c om
        converttoraw();
        FileReader fr = new FileReader("RawData.txt");
        BufferedReader br = new BufferedReader(fr);
        LineNumberReader lnr = new LineNumberReader(new FileReader(new File("RawData.txt")));
        lnr.skip(Long.MAX_VALUE);
        int lineNum = lnr.getLineNumber();
        System.out.println(lineNum);
        lnr.close();
        Connect connect = new Connect();
        ResultSet rs = connect.connectSelect("1", "SELECT * FROM ROOT.STOCK");
        ArrayList<String> stringList = new ArrayList<>();
        while (rs.next()) {
            String sym = rs.getString("symbol");
            System.out.println(sym);
            stringList.add(sym);
        }
        for (int i = 0; i < lineNum; i++) {
            String lineNumber = br.readLine();
            String[] parts = lineNumber.split(",");
            String name = parts[0];
            String symbol = parts[1];
            if (stringList.contains(symbol)) {
                System.out.println(symbol + " : Is Already Added");
            } else if (symbol.length() > 4) {
                System.out.println(symbol + " : Is Not a Stock Symbol");
            } else {
                connect.connectInsert("INSERT INTO STOCK VALUES ('" + symbol + "','" + name + "')");
            }
        }
        br.close();
        fr.close();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
    try {
        displayStock();
    } catch (Exception ex) {
        Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static String getManifestEntryAttrs(JarFile jar, String entryName) throws IOException {

    // Get full manifest content
    String manifestContent = getManifest(jar);

    LineNumberReader lnr = new LineNumberReader(new StringReader(manifestContent));

    try {//from  w ww. jav a  2  s .c  o m
        StringBuilder sb = new StringBuilder();

        String line = null;

        // First entry name attribute to match
        String entryNameAttr = createAttributeText(NAME_ATTR, entryName);

        // Only match on first 70 characters (max line length)
        if (entryNameAttr.length() > 70) {
            entryNameAttr = entryNameAttr.substring(0, 70);
        }

        // Keep reading and ignoring lines until entry is found - the end of the entry's attributes
        while ((line = lnr.readLine()) != null) {
            if (line.equals(entryNameAttr)) {
                // Found entry name attribute - append it
                sb.append(line);
                sb.append(CRLF);
                break;
            }
        }

        // Keep reading until a blank line is found - the end of the entry's
        // attributes
        while ((line = lnr.readLine()) != null) {
            if (line.trim().length() == 0) {
                break;
            }

            // Append another entry attribute line
            sb.append(line);
            sb.append(CRLF);
        }

        return sb.toString();
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}

From source file:org.apache.maven.dotnet.AbstractDotNetMojo.java

/**
 * Exports a resource folder to a subdirectory of the maven build directory. <br/>
 * The folder is supposed to contain a "context.txt" file that contains the
 * list of the files to export, one name per line
 * //w w w . ja va  2 s.c o m
 * @param resourceDir
 *          the resource directory to export
 * @param destinationSubFolder
 *          the subfolder to use, that will be created under
 *          ${project.build.dir}
 * @param application
 *          the exported application
 * @return the generated folder
 * @throws MojoExecutionException
 */
protected File extractFolder(String resourceDir, String destinationSubFolder, String application)
        throws MojoExecutionException {
    if (!useEmbbededRuntime) {
        getLog().warn(
                "The use of the embedded runtime package is not enabled. Please add the settings 'dotnet.use.embedded.runtime=true'");
        throw new MojoExecutionException(
                "The use of the embedded runtime package is not enabled for " + application);
    }
    getLog().debug("Exporting files for " + application);
    String contentFile = resourceDir + "/" + CONTENT_FILE_NAME;

    InputStream contentResource = getClassLoader().getResourceAsStream(contentFile);

    if (contentResource == null) {
        throw new MojoExecutionException(application + " binaries were not found");
    }

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(contentResource));
    String line = null;
    List<String> contentFiles = new ArrayList<String>();
    try {
        while ((line = reader.readLine()) != null) {
            contentFiles.add(line.trim());
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Could not extract the files for " + application, e);
    }
    File reportDirectory = getReportDirectory();
    File extractFolder = new File(reportDirectory, destinationSubFolder);
    extractResources(extractFolder, resourceDir, contentFiles, application);
    return extractFolder;
}

From source file:com.saptarshidebnath.lib.processrunner.process.RunnerFactoryTest.java

private int getFileLineNumber(final File fileToCountLineNumber) throws IOException {
    LineNumberReader lnr = null;/*from   w  w w . j  a  va 2s  .c o  m*/
    int lineNumber;
    try {
        lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(fileToCountLineNumber)));
        long skipValue = Long.MAX_VALUE;
        while (skipValue != 0) {
            skipValue = lnr.skip(Long.MAX_VALUE);
        }
        lineNumber = lnr.getLineNumber() + 1; // Add 1 because line index starts at 0
    } finally {
        if (lnr != null) {
            lnr.close();
        }
    }
    return lineNumber;
}

From source file:ua.utility.kfsdbupgrade.App.java

/**
 * Read SQL statements from the provided {@link File} into a {@link List} of
 * {@link String}s. Blank lines and comment lines (lines beginning with
 * "<code>--</code>") are skipped.
 * //from  ww w. j  av a2 s  .  c  o m
 * @param f
 *            {@link File} to read SQL statements from
 * @return {@link List} of {@link String}s representing the SQL statements
 *         to execute read from the provided {@link File}
 */
private List<String> getSqlStatements(File f) {
    List<String> retval = new ArrayList<String>();
    LineNumberReader lnr = null;

    try {
        lnr = new LineNumberReader(new FileReader(f));
        String line = null;
        StringBuilder sql = new StringBuilder(512);

        while ((line = lnr.readLine()) != null) {
            if (StringUtils.isNotBlank(line) && !line.trim().startsWith("--")) {
                line = line.trim();
                // FIXME hardcoded delimiters
                if (line.equals("/") || line.equals(";")) {
                    if (sql.length() > 0) {
                        retval.add(sql.toString());
                        sql.setLength(0);
                    }
                } else if (line.endsWith("/") || line.endsWith(";")) {
                    sql.append(" ");
                    sql.append(line.substring(0, line.length() - 1));
                    retval.add(sql.toString());
                    sql.setLength(0);
                } else {
                    sql.append(" ");
                    sql.append(line);
                }
            }
        }

        if (sql.length() > 0) {
            retval.add(sql.toString());
        }
    } catch (Exception ex) {
        LOGGER.error(ex);
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
        } catch (Exception ex) {
        }
    }

    return retval;
}

From source file:org.hyperic.snmp.MIBTree.java

private boolean parseMIB(InputStream is) throws IOException {
    String line;/*w w  w. j  a v a 2 s  .c o m*/

    this.reader = new LineNumberReader(new InputStreamReader(is));

    this.currentMIB = "";

    tokenize(readLine());

    if (!token(1).equals("DEFINITIONS")) {
        return false;
    }

    this.currentMIB = token(0);

    int size = this.table.size();

    while ((line = readLine()) != null) {
        tokenize(line);

        String first = token(0);

        if (first.equals("IMPORTS") || first.equals("EXPORTS")) {
            readToLine(";");

            continue;
        }

        if (first.equals("SYNTAX")) {
            continue;
        }

        String second = token(1);

        if (second == null) {
            continue;
        }

        if ((line.indexOf("SEQUENCE {") != -1) || (line.indexOf("CHOICE {") != -1)) {
            readToLine("}");
        } else if (second.equals("OBJECT") && token(2).equals("IDENTIFIER")) {
            parseObjectIdentifier(line);
        } else if ((this.previous.size() == 1) && first.equals("OBJECT") && second.equals("IDENTIFIER")) {
            // snmpFrameworkAdmin
            // OBJECT IDENTIFIER ::= { snmpFrameworkMIB 1 }
            Object name = this.previous.get(0);

            line = name + " " + line;

            this.tokens.add(0, name);

            parseObjectIdentifier(line);
        } else if (second.equals("OBJECT-TYPE") || second.equals("MODULE-IDENTITY")
                || second.equals("OBJECT-IDENTITY")) {
            parseObjectType();
        }
    }

    if (log.isDebugEnabled()) {
        log.debug(this.currentMIB + " added " + (this.table.size() - size) + " entries");
    }

    return true;
}

From source file:nl.uva.illc.dataselection.InvitationModel.java

public static void readFiles() throws IOException, InterruptedException {

    log.info("Reading files");

    src_codes = HashObjIntMaps.newMutableMap();
    trg_codes = HashObjIntMaps.newMutableMap();
    src_codes.put(null, 0);// w  w  w  .ja  va 2  s .  com
    trg_codes.put(null, 0);

    LineNumberReader lr = new LineNumberReader(new FileReader(IN + "." + SRC));
    lr.skip(Long.MAX_VALUE);
    int indomain_size = lr.getLineNumber();
    lr.close();

    lr = new LineNumberReader(new FileReader(MIX + "." + SRC));
    lr.skip(Long.MAX_VALUE);
    int mixdomain_size = lr.getLineNumber();
    lr.close();

    src_indomain = new int[indomain_size][];
    trg_indomain = new int[indomain_size][];
    src_mixdomain = new int[mixdomain_size][];
    trg_mixdomain = new int[mixdomain_size][];

    latch = new CountDownLatch(2);
    readFile(IN + "." + SRC, src_codes, src_indomain);
    readFile(IN + "." + TRG, trg_codes, trg_indomain);
    latch.await();

    latch = new CountDownLatch(2);
    readFile(MIX + "." + SRC, src_codes, src_mixdomain);
    readFile(MIX + "." + TRG, trg_codes, trg_mixdomain);
    latch.await();

}

From source file:org.opencms.setup.CmsSetupDb.java

/**
 * Internal method to parse and execute a setup script.<p>
 *
 * @param inputReader an input stream reader on the setup script
 * @param replacers the replacements to perform in the script
 * @param abortOnError if a error occurs this flag indicates if to continue or to abort
 *///from   w ww .j  a  v a  2s . com
private void executeSql(Reader inputReader, Map<String, String> replacers, boolean abortOnError) {

    String statement = "";
    LineNumberReader reader = null;
    String line = null;

    // parse the setup script
    try {
        reader = new LineNumberReader(inputReader);

        while (true) {
            line = reader.readLine();
            if (line == null) {
                break;
            }
            StringTokenizer st = new StringTokenizer(line);

            while (st.hasMoreTokens()) {
                String currentToken = st.nextToken();

                // comment! Skip rest of the line
                if (currentToken.startsWith("#")) {
                    break;
                }

                // not to be executed
                if (currentToken.startsWith("prompt")) {
                    break;
                }

                // add token to query
                statement += " " + currentToken;

                // query complete (terminated by ';')
                if (currentToken.endsWith(";")) {
                    // cut of ';' at the end
                    statement = statement.substring(0, (statement.length() - 1));

                    // normal statement, execute it
                    try {
                        if (replacers != null) {
                            statement = replaceTokens(statement, replacers);
                            executeStatement(statement);
                        } else {
                            executeStatement(statement);
                        }
                    } catch (SQLException e) {
                        if (!abortOnError) {
                            if (m_errorLogging) {
                                m_errors.add("Error executing SQL statement: " + statement);
                                m_errors.add(CmsException.getStackTraceAsString(e));
                            }
                        } else {
                            throw e;
                        }
                    }

                    // reset
                    statement = "";
                }
            }

            statement += " \n";
        }
    } catch (SQLException e) {
        if (m_errorLogging) {
            m_errors.add("Error executing SQL statement: " + statement);
            m_errors.add(CmsException.getStackTraceAsString(e));
        }
    } catch (Exception e) {
        if (m_errorLogging) {
            m_errors.add("Error parsing database setup SQL script in line: " + line);
            m_errors.add(CmsException.getStackTraceAsString(e));
        }
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            // noop
        }
    }
}