Example usage for java.io LineNumberReader getLineNumber

List of usage examples for java.io LineNumberReader getLineNumber

Introduction

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

Prototype

public int getLineNumber() 

Source Link

Document

Get the current line number.

Usage

From source file:gtu._work.etc.GoogleContactUI.java

void googleTableMouseClicked(MouseEvent evt) {
    try {//from www.ja  va  2s.c o m
        JPopupMenuUtil popupUtil = JPopupMenuUtil.newInstance(googleTable).applyEvent(evt);

        //CHANGE ENCODE
        popupUtil.addJMenuItem("set encode", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String code = StringUtils.defaultString(JOptionPaneUtil.newInstance().iconPlainMessage()
                            .showInputDialog("input file encode", "ENCODE"), "UTF8");
                    encode = Charset.forName(code).displayName();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
                System.err.println("encode : " + encode);
            }
        });

        //SIMPLE LOAD GOOGLE CSV FILE
        popupUtil.addJMenuItem("open Google CSV file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile("csv", ".csv")
                        .showOpenDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                try {
                    if (file.getName().endsWith(".csv")) {
                        DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                        LineNumberReader reader = new LineNumberReader(
                                new InputStreamReader(new FileInputStream(file), GOOGLE_CVS_ENCODE));
                        for (String line = null; (line = reader.readLine()) != null;) {
                            if (reader.getLineNumber() == 1) {
                                continue;
                            }
                            model.addRow(line.split(","));
                        }
                        reader.close();
                        googleTable.setModel(model);
                        JTableUtil.newInstance(googleTable).hiddenAllEmptyColumn();
                    }
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //SAVE CSV FILE FOR GOOGLE
        popupUtil.addJMenuItem("save to Google CVS file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile(".csv", ".csv")
                        .showSaveDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                file = FileUtil.getIndicateFileExtension(file, ".csv");
                try {
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(file), GOOGLE_CVS_ENCODE));
                    StringBuilder sb = new StringBuilder();
                    for (Object title : googleColumns) {
                        sb.append(title + ",");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    System.out.println(sb);
                    writer.write(sb.toString());
                    writer.newLine();
                    DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                    for (int row = 0; row < model.getRowCount(); row++) {
                        sb = new StringBuilder();
                        for (int col = 0; col < model.getColumnCount(); col++) {
                            String colVal = StringUtils.defaultString((String) model.getValueAt(row, col), "");
                            if (colVal.equalsIgnoreCase("null")) {
                                colVal = "";
                            }
                            sb.append(colVal + ",");
                        }
                        sb.deleteCharAt(sb.length() - 1);
                        System.out.println(sb);
                        writer.write(sb.toString());
                        writer.newLine();
                    }
                    writer.flush();
                    writer.close();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //PASTE CLIPBOARD
        popupUtil.addJMenuItem("paste clipboard", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_multiRowData(true);
            }
        });

        popupUtil.addJMenuItem("paste clipboard to selected cell", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_singleValueToSelectedCell();
            }
        });

        JMenuItem addEmptyRowItem = JTableUtil.newInstance(googleTable).jMenuItem_addRow(false,
                "add row count?");
        addEmptyRowItem.setText("add row");
        JMenuItem removeColumnItem = JTableUtil.newInstance(googleTable).jMenuItem_removeColumn(null);
        removeColumnItem.setText("remove column");
        JMenuItem removeRowItem = JTableUtil.newInstance(googleTable).jMenuItem_removeRow(null);
        removeRowItem.setText("remove row");
        JMenuItem removeAllRowItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_removeAllRow("remove all row?");
        removeAllRowItem.setText("remove all row");
        JMenuItem clearSelectedCellItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_clearSelectedCell("are you sure clear selected area?");
        clearSelectedCellItem.setText("clear selected area");
        popupUtil.addJMenuItem(addEmptyRowItem, removeColumnItem, removeRowItem, removeAllRowItem,
                clearSelectedCellItem);
        popupUtil.show();
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:ru.jkff.antro.ProfileListener.java

private Map<String, AnnotatedFile> getAnnotatedFiles() {
    Map<String, AnnotatedFile> res = new HashMap<String, AnnotatedFile>();

    Map<OurLocation, Stat> statsByLoc = getStatsByLocation();
    for (String file : getUsedBuildFiles()) {
        List<String> lines = new ArrayList<String>();
        List<Stat> stats = new ArrayList<Stat>();

        try {//from ww  w.  j av  a2  s  .c o  m
            LineNumberReader r = new LineNumberReader(new FileReader(file));
            String line;
            while (null != (line = r.readLine())) {
                OurLocation loc = new OurLocation(file, r.getLineNumber());

                Stat stat = statsByLoc.get(loc);
                lines.add(line);
                stats.add(stat);
            }
        } catch (IOException e) {
        }

        res.put(file, new AnnotatedFile(lines.toArray(new String[0]), stats.toArray(new Stat[0]), file));
    }

    return res;
}

From source file:com.datatorrent.stram.StramLocalClusterTest.java

/**
 * Verify test configuration launches and stops after input terminates.
 * Test validates expected output end to end.
 *
 * @throws Exception//from  ww w .j ava  2  s  . co m
 */
@Test
public void testLocalClusterInitShutdown() throws Exception {
    TestGeneratorInputOperator genNode = dag.addOperator("genNode", TestGeneratorInputOperator.class);
    genNode.setMaxTuples(2);

    GenericTestOperator node1 = dag.addOperator("node1", GenericTestOperator.class);
    node1.setEmitFormat("%s >> node1");

    File outFile = new File(
            "./target/" + StramLocalClusterTest.class.getName() + "-testLocalClusterInitShutdown.out");
    outFile.delete();

    TestOutputOperator outNode = dag.addOperator("outNode", TestOutputOperator.class);
    outNode.pathSpec = outFile.toURI().toString();

    dag.addStream("fromGenNode", genNode.outport, node1.inport1);

    dag.addStream("fromNode1", node1.outport1, outNode.inport);

    dag.getAttributes().put(LogicalPlan.CONTAINERS_MAX_COUNT, 2);

    StramLocalCluster localCluster = new StramLocalCluster(dag);
    localCluster.setHeartbeatMonitoringEnabled(false);
    localCluster.run();

    Assert.assertTrue(outFile + " exists", outFile.exists());
    LineNumberReader lnr = new LineNumberReader(new FileReader(outFile));
    String line;
    while ((line = lnr.readLine()) != null) {
        Assert.assertTrue("line match " + line, line.matches("" + lnr.getLineNumber() + " >> node1"));
    }
    Assert.assertEquals("number lines", 2, lnr.getLineNumber());
    lnr.close();
}

From source file:pl.otros.logview.importer.UtilLoggingXmlLogImporter.java

@Override
public void importLogs(InputStream in, LogDataCollector collector, ParsingContext parsingContext) {

    StringBuffer sb = new StringBuffer();
    try {//from w ww . j av  a  2s.  c  om
        LineNumberReader bin = new LineNumberReader(new InputStreamReader(in, ENCODING));
        String line = null;

        while ((line = bin.readLine()) != null) {
            sb.append(line).append("\n");
            if (bin.getLineNumber() % 30 == 0) {
                decodeEvents(sb.toString(), collector, parsingContext);
                sb.setLength(0);
            }
        }

    } catch (UnsupportedEncodingException e) {
        LOGGER.severe("Cant load codepage " + e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        decodeEvents(sb.toString(), collector, parsingContext);
    }

}

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 {//w ww.java2s  .  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:gpl.pierrick.brihaye.aramorph.InMemoryDictionaryHandler.java

/** Loads a dictionary into a <CODE>Set</CODE> where the <PRE>key</PRE> is entry and its <PRE>value</PRE> is a
 * <CODE>List</CODE> (each entry can have multiple values)
 * @param set The set//from  ww w .  j  a va 2 s. c o  m
 * @param name A human-readable name
 * @param is The stream
 * @throws RuntimeException If a problem occurs when reading the dictionary
 */
private void loadDictionary(Map set, String name, InputStream is) throws RuntimeException { //TODO : should be static
    HashSet lemmas = new HashSet();
    int forms = 0;
    String lemmaID = "";
    System.out.print("Loading dictionary : " + name + " ");
    try {
        LineNumberReader IN = new LineNumberReader(new InputStreamReader(is, "ISO8859_1"));
        String line = null;
        while ((line = IN.readLine()) != null) {
            if ((IN.getLineNumber() % 1000) == 1)
                System.out.print(".");
            // new lemma
            if (line.startsWith(";; ")) {
                lemmaID = line.substring(3);
                // lemmaID's must be unique
                if (lemmas.contains(lemmaID))
                    throw new RuntimeException("Lemma " + lemmaID + "in " + name + " (line "
                            + IN.getLineNumber() + ") isn't unique");
                lemmas.add(lemmaID);
            }
            // comment
            else if (line.startsWith(";")) {
            } else {
                String split[] = line.split("\t", -1); //-1 to avoid triming of trail values

                //a little error-checking won't hurt :
                if (split.length != 4) {
                    throw new RuntimeException("Entry in " + name + " (line " + IN.getLineNumber()
                            + ") doesn't have 4 fields (3 tabs)");
                }
                String entry = split[0]; // get the entry for use as key
                String vocalization = split[1];
                String morphology = split[2];
                String glossPOS = split[3];

                String gloss;
                String POS;

                Pattern p;
                Matcher m;

                // two ways to get the POS info:
                // (1) explicitly, by extracting it from the gloss field:
                p = Pattern.compile(".*" + "<pos>(.+?)</pos>" + ".*");
                m = p.matcher(glossPOS);
                if (m.matches()) {
                    POS = m.group(1); //extract POS from glossPOS
                    gloss = glossPOS; //we clean up the gloss later (see below)
                }
                // (2) by deduction: use the morphology (and sometimes the voc and gloss) to deduce the appropriate POS
                else {
                    // we need the gloss to guess proper names
                    gloss = glossPOS;
                    // null prefix or suffix
                    if (morphology.matches("^(Pref-0|Suff-0)$")) {
                        POS = "";
                    } else if (morphology.matches("^F" + ".*")) {
                        POS = vocalization + "/FUNC_WORD";
                    } else if (morphology.matches("^IV" + ".*")) {
                        POS = vocalization + "/VERB_IMPERFECT";
                    } else if (morphology.matches("^PV" + ".*")) {
                        POS = vocalization + "/VERB_PERFECT";
                    } else if (morphology.matches("^CV" + ".*")) {
                        POS = vocalization + "/VERB_IMPERATIVE";
                    } else if (morphology.matches("^N" + ".*")) {
                        // educated guess (99% correct)
                        if (gloss.matches("^[A-Z]" + ".*")) {
                            POS = vocalization + "/NOUN_PROP";
                        }
                        // (was NOUN_ADJ: some of these are really ADJ's and need to be tagged manually)
                        else if (vocalization.matches(".*" + "iy~$")) {
                            POS = vocalization + "/NOUN";
                        } else
                            POS = vocalization + "/NOUN";
                    } else {
                        throw new RuntimeException(
                                "No POS can be deduced in " + name + " (line " + IN.getLineNumber() + ")");
                    }
                }

                // clean up the gloss: remove POS info and extra space, and convert upper-ASCII  to lower (it doesn't convert well to UTF-8)
                gloss = gloss.replaceFirst("<pos>.+?</pos>", "");
                gloss = gloss.trim();
                //TODO : we definitely need a translate() method in the java packages !
                gloss = gloss.replaceAll(";", "/"); //TODO : is it necessary ?
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "A");
                gloss = gloss.replaceAll("", "C");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "E");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "I");
                gloss = gloss.replaceAll("", "N");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "O");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "U");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "a");
                gloss = gloss.replaceAll("", "c");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "e");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "i");
                gloss = gloss.replaceAll("", "n");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "o");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "u");
                gloss = gloss.replaceAll("", "AE");
                gloss = gloss.replaceAll("", "Sh");
                gloss = gloss.replaceAll("", "Zh");
                gloss = gloss.replaceAll("", "ss");
                gloss = gloss.replaceAll("", "ae");
                gloss = gloss.replaceAll("", "sh");
                gloss = gloss.replaceAll("", "zh");
                // note that although we read 4 fields from the dict we now save 5 fields in the hash table
                // because the info in last field, glossPOS, was split into two: gloss and POS
                DictionaryEntry de = new DictionaryEntry(entry, lemmaID, vocalization, morphology, gloss, POS);
                if (set.containsKey(entry)) {
                    ((Collection) set.get(entry)).add(de);
                } else
                    set.put(entry, de);
                forms++;
            }
        }
        IN.close();
        System.out.println();
        if (!"".equals(lemmaID))
            System.out.print(lemmas.size() + " lemmas and ");
        System.out.println(set.size() + " entries totalizing " + forms + " forms");
    } catch (IOException e) {
        throw new RuntimeException("Can not open : " + name);
    }
}

From source file:de.upb.timok.run.GenericSmacPipeline.java

private void splitTrainTestFile(String timedInputFile, String timedInputTrainFile, String timedInputTestFile,
        double trainPercentage, double testPercentage, double anomalyPercentage, boolean isRti)
        throws IOException {
    logger.info("TimedInputFile=" + timedInputFile);
    final File f = new File(timedInputFile);
    System.out.println(f);/*from   w w w.j a va 2s . c  om*/
    final LineNumberReader lnr = new LineNumberReader(new FileReader(timedInputFile));
    lnr.skip(Long.MAX_VALUE);
    int samples = lnr.getLineNumber();
    lnr.close();
    final int trainingSamples = (int) (samples * trainPercentage);
    final int testSamples = (int) (samples * testPercentage);
    final int anomalies = (int) (anomalyPercentage * testSamples);
    final int writtenTrainingSamples = 0;
    final int writtenTestSamples = 0;
    int insertedAnomalies = 0;
    final BufferedReader br = Files.newBufferedReader(Paths.get(timedInputFile), StandardCharsets.UTF_8);
    String line = null;
    final BufferedWriter trainWriter = Files.newBufferedWriter(Paths.get(timedInputTrainFile),
            StandardCharsets.UTF_8);
    final BufferedWriter testWriter = Files.newBufferedWriter(Paths.get(timedInputTestFile),
            StandardCharsets.UTF_8);
    final Random r = new Random(MasterSeed.nextLong());
    final Random mutation = new Random(MasterSeed.nextLong());
    boolean force = false;
    int lineIndex = 0;
    int linesLeft;
    int anomaliesToInsert;
    if (isRti) {
        br.readLine();
        samples--;
    }
    while ((line = br.readLine()) != null) {
        if (writtenTrainingSamples < trainingSamples && writtenTestSamples < testSamples) {
            // choose randomly according to train/test percentage
            if (r.nextDouble() > testPercentage) {
                // write to train
                writeSample(new TimedSequence(line, true, false).toTrebaString(), trainWriter);
            } else {
                // write to test
                insertedAnomalies = testAndWriteAnomaly(anomalies, insertedAnomalies, anomalyPercentage, line,
                        testWriter, mutation, force);
            }
        } else if (writtenTrainingSamples >= trainingSamples) {
            insertedAnomalies = testAndWriteAnomaly(anomalies, insertedAnomalies, anomalyPercentage, line,
                    testWriter, mutation, force);
        } else if (writtenTestSamples >= testSamples) {
            // only write trainSamples from now on
            writeSample(new TimedSequence(line, true, false).toTrebaString(), trainWriter);
        }
        lineIndex++;
        linesLeft = samples - lineIndex;
        anomaliesToInsert = anomalies - insertedAnomalies;
        if (linesLeft <= anomaliesToInsert) {
            force = true;
        }
    }
    br.close();
    trainWriter.close();
    testWriter.close();
}

From source file:com.bigdata.rdf.sail.webapp.AbstractTestNanoSparqlClient.java

/**
 * Read the contents of a file.//ww w.j a  v  a 2  s  . c om
 * 
 * @param file
 *            The file.
 * @return It's contents.
 */
protected static String readFromFile(final File file) throws IOException {

    final LineNumberReader r = new LineNumberReader(new FileReader(file));

    try {

        final StringBuilder sb = new StringBuilder();

        String s;
        while ((s = r.readLine()) != null) {

            if (r.getLineNumber() > 1)
                sb.append("\n");

            sb.append(s);

        }

        return sb.toString();

    } finally {

        r.close();

    }

}

From source file:org.kalypso.kalypsomodel1d2d.sim.IterationInfoTelemac.java

@Override
public void readIterFile() throws IOException {
    m_itrFile.refresh();/*from  w  w  w  .j a v a2 s  .  c  om*/
    if (!m_itrFile.exists())
        return;

    /* Read file and write outputs */
    LineNumberReader lnr = null;
    try {
        final byte[] content = FileUtil.getContent(m_itrFile);
        lnr = new LineNumberReader(new StringReader(new String(content, Charset.defaultCharset())));
        while (lnr.ready()) {
            final String line = lnr.readLine();
            if (line == null)
                break;
            processLine(line, lnr.getLineNumber());
        }
    } catch (final FileNotFoundException e) {
        if (lnr == null)
            StatusUtilities.createStatus(IStatus.WARNING, ISimulation1D2DConstants.CODE_RMA10S,
                    Messages.getString("org.kalypso.kalypsomodel1d2d.sim.IterationInfo.1"), e); //$NON-NLS-1$

        final String msg = Messages.getString("org.kalypso.kalypsomodel1d2d.sim.IterationInfo.2", //$NON-NLS-1$
                lnr.getLineNumber());
        StatusUtilities.createStatus(IStatus.WARNING, ISimulation1D2DConstants.CODE_RMA10S, msg, e);
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.IterationInfoSWAN.java

@Override
public void readIterFile() throws IOException {
    m_itrFile.refresh();/*from  w w w . j a  v a2s  . com*/
    if (!m_itrFile.exists())
        return;

    /* Read file and write outputs */
    LineNumberReader lnr = null;
    try {
        final byte[] content = FileUtil.getContent(m_itrFile);
        lnr = new LineNumberReader(new StringReader(new String(content, Charset.defaultCharset())));
        while (lnr.ready()) {
            final String line = lnr.readLine();
            if (line == null)
                break;
            processLine(line, lnr.getLineNumber());
        }
    } catch (final FileNotFoundException e) {
        // FIXME: these stati are never used; what happened here?
        //      if( lnr == null )
        //        StatusUtilities.createStatus( IStatus.WARNING, ISimulation1D2DConstants.CODE_RMA10S, Messages.getString( "org.kalypso.kalypsomodel1d2d.sim.IterationInfo.1" ), e ); //$NON-NLS-1$
        //
        //      final String msg = Messages.getString( "org.kalypso.kalypsomodel1d2d.sim.IterationInfo.2", lnr.getLineNumber() ); //$NON-NLS-1$
        //      StatusUtilities.createStatus( IStatus.WARNING, ISimulation1D2DConstants.CODE_RMA10S, msg, e );
    } finally {
        IOUtils.closeQuietly(lnr);
    }
}