Example usage for java.io LineNumberReader readLine

List of usage examples for java.io LineNumberReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Read a line of text.

Usage

From source file:org.kalypso.wspwin.core.WspWinZustand.java

private static ZustandSegmentBean[] readZustandSegments(final LineNumberReader reader, final int segmentCount,
        final String filename) throws ParseException, IOException {
    final List<ZustandSegmentBean> beans = new ArrayList<>(20);

    int readSegments = 0;
    while (reader.ready()) {
        final String line = reader.readLine();
        /* Skip empty lines; we have WspWin projects with and without a separating empty line */
        if (StringUtils.isBlank(line))
            continue;

        final StringTokenizer tokenizer = new StringTokenizer(line);
        if (tokenizer.countTokens() != 7)
            throw new ParseException(Messages.getString("org.kalypso.wspwin.core.WspWinZustand.2", filename, //$NON-NLS-1$
                    reader.getLineNumber()), reader.getLineNumber());

        try {//from   www.  j a v  a 2s.  c o  m
            final BigDecimal stationFrom = new BigDecimal(tokenizer.nextToken());
            final BigDecimal stationTo = new BigDecimal(tokenizer.nextToken());
            final double distanceVL = Double.parseDouble(tokenizer.nextToken());
            final double distanceHF = Double.parseDouble(tokenizer.nextToken());
            final double distanceVR = Double.parseDouble(tokenizer.nextToken());

            final String fileNameFrom = tokenizer.nextToken();
            final String fileNameTo = tokenizer.nextToken();

            final ZustandSegmentBean bean = new ZustandSegmentBean(stationFrom, stationTo, fileNameFrom,
                    fileNameTo, distanceVL, distanceHF, distanceVR);
            beans.add(bean);

            readSegments++;
        } catch (final NumberFormatException e) {
            e.printStackTrace();
            throw new ParseException(Messages.getString("org.kalypso.wspwin.core.WspWinZustand.3", filename, //$NON-NLS-1$
                    reader.getLineNumber()), reader.getLineNumber());
        }
    }

    if (readSegments != segmentCount)
        throw new ParseException(
                Messages.getString("org.kalypso.wspwin.core.WspWinZustand.1", filename, reader.getLineNumber()), //$NON-NLS-1$
                reader.getLineNumber());

    return beans.toArray(new ZustandSegmentBean[beans.size()]);
}

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

public static void readLocationNamesToSuppress() {
    String suppress_file = "suppress.locations.txt.gz";
    try {//from ww  w.j a v a2 s  .c  o  m
        InputStream is = new GZIPInputStream(NER.class.getClassLoader().getResourceAsStream(suppress_file));
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
        while (true) {
            String line = lnr.readLine();
            if (line == null)
                break;
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String s = st.nextToken();
                if (!s.startsWith("#"))
                    locationsToSuppress.add(s.toLowerCase());
            }
        }
    } catch (Exception e) {
        log.warn("Error: unable to read " + suppress_file);
        Util.print_exception(e);
    }
    log.info(locationsToSuppress.size() + " names to suppress as locations");
}

From source file:net.sqs2.util.FileUtil.java

/**
 * keyword replace in stream (replacing string cannot contain newline
 * chars)./*from  ww  w  . j  a  v a  2  s.  co  m*/
 * 
 * @param inputStream
 * @param outputStream
 * @param from
 *            keyword(from)
 * @param to
 *            keyword(to)
 * @param encoding
 *            file encoding
 * @return true: some keywords replaced, false: no keyword replaced
 */
public static boolean keywordSubstitution(InputStream inputStream, OutputStream outputStream, String from,
        String to, String encoding) {
    boolean modified = false;
    try {
        PrintWriter writer = new PrintWriter(
                new OutputStreamWriter(new BufferedOutputStream(outputStream), encoding));
        LineNumberReader reader = new LineNumberReader(
                new InputStreamReader(new BufferedInputStream(inputStream), encoding));
        String line = null;
        while ((line = reader.readLine()) != null) {
            String result = StringUtil.replaceAll(line, from, to);
            writer.println(result);
            if (!result.equals(line)) {
                modified |= true;
            }
        }
        reader.close();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        new RuntimeException(e);
    }
    return modified;
}

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

public static void readLocationsWG() {
    try {/*from w  ww .j  a  v a  2 s. c o  m*/
        InputStream is = new GZIPInputStream(
                NER.class.getClassLoader().getResourceAsStream("WG.locations.txt.gz"));
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
        while (true) {
            String line = lnr.readLine();
            if (line == null)
                break;
            StringTokenizer st = new StringTokenizer(line, "\t");
            if (st.countTokens() == 4) {
                String locationName = st.nextToken();
                String canonicalName = locationName.toLowerCase();
                if (locationsToSuppress.contains(canonicalName))
                    continue;
                String lat = st.nextToken();
                String longi = st.nextToken();
                String pop = st.nextToken();
                long popl = Long.parseLong(pop);
                float latf = ((float) Integer.parseInt(lat)) / 100.0f;
                float longif = ((float) Integer.parseInt(longi)) / 100.0f;
                Long existingPop = populations.get(canonicalName);
                if (existingPop == null || popl > existingPop) {
                    populations.put(canonicalName, popl);
                    locations.put(canonicalName,
                            new LocationInfo(locationName, Float.toString(latf), Float.toString(longif)));
                }
            }
        }
    } catch (Exception e) {
        log.warn("Unable to read World Gazetteer file, places info may be inaccurate");
        log.debug(Util.stackTrace(e));
    }
}

From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java

public static void stop(final Log LOG, final ProcessDescription cfg) throws Exception {
    boolean isNew = false;

    if (cfg.getProcess() != null || isNew) {
        LOG.info("Stopping Launchpad " + cfg.getId());
        boolean destroy = true;
        final int twoMinutes = 2 * 60 * 1000;
        final File controlPortFile = getControlPortFile(cfg.getDirectory());
        LOG.debug("Control port file " + controlPortFile + " exists: " + controlPortFile.exists());
        if (controlPortFile.exists()) {
            // reading control port
            int controlPort = -1;
            String secretKey = null;
            LineNumberReader lnr = null;
            String serverName = null;
            try {
                lnr = new LineNumberReader(new FileReader(controlPortFile));
                final String portLine = lnr.readLine();
                final int pos = portLine.indexOf(':');
                controlPort = Integer.parseInt(portLine.substring(pos + 1));
                if (pos > 0) {
                    serverName = portLine.substring(0, pos);
                }/*from w w  w  .  ja  v  a 2s  .  c o  m*/
                secretKey = lnr.readLine();
            } catch (final NumberFormatException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } catch (final IOException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } finally {
                IOUtils.closeQuietly(lnr);
            }

            if (controlPort != -1) {
                final List<String> hosts = new ArrayList<String>();
                if (serverName != null) {
                    hosts.add(serverName);
                }
                hosts.add("localhost");
                hosts.add("127.0.0.1");
                LOG.debug("Found control port " + controlPort);
                int index = 0;
                while (destroy && index < hosts.size()) {
                    final String hostName = hosts.get(index);

                    Socket clientSocket = null;
                    DataOutputStream out = null;
                    BufferedReader in = null;
                    try {
                        LOG.debug("Trying to connect to " + hostName + ":" + controlPort);
                        clientSocket = new Socket();
                        // set a socket timeout
                        clientSocket.connect(new InetSocketAddress(hostName, controlPort), twoMinutes);
                        // without that, read() call on the InputStream associated with this Socket is infinite
                        clientSocket.setSoTimeout(twoMinutes);

                        LOG.debug(hostName + ":" + controlPort
                                + " connection estabilished, sending the 'stop' command...");

                        out = new DataOutputStream(clientSocket.getOutputStream());
                        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        if (secretKey != null) {
                            out.writeBytes(secretKey);
                            out.write(' ');
                        }
                        out.writeBytes("stop\n");
                        in.readLine();
                        destroy = false;
                        LOG.debug("'stop' command sent to " + hostName + ":" + controlPort);
                    } catch (final Throwable ignore) {
                        // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions
                        // we ignore this for now
                        LOG.debug("Error sending 'stop' command to " + hostName + ":" + controlPort
                                + " due to: " + ignore.getMessage());
                    } finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                        IOUtils.closeQuietly(clientSocket);
                    }
                    index++;
                }
            }
        }
        if (cfg.getProcess() != null) {
            final Process process = cfg.getProcess();

            if (!destroy) {
                // as shutdown might block forever, we use a timeout
                final long now = System.currentTimeMillis();
                final long end = now + twoMinutes;

                LOG.debug("Waiting for process to stop...");

                while (isAlive(process) && (System.currentTimeMillis() < end)) {
                    try {
                        Thread.sleep(2500);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
                if (isAlive(process)) {
                    LOG.debug("Process timeout out after 2 minutes");
                    destroy = true;
                } else {
                    LOG.debug("Process stopped");
                }
            }

            if (destroy) {
                LOG.debug("Destroying process...");
                process.destroy();
                LOG.debug("Process destroyed");
            }

            cfg.setProcess(null);
        }
    } else {
        LOG.warn("Launchpad already stopped");
    }
}

From source file:org.locationtech.jtstest.util.StringUtil.java

public static String getStackTrace(Throwable t, int depth) {
    String stackTrace = "";
    StringReader stringReader = new StringReader(getStackTrace(t));
    LineNumberReader lineNumberReader = new LineNumberReader(stringReader);
    for (int i = 0; i < depth; i++) {
        try {/*w  w  w .  j ava2s .  c om*/
            stackTrace += lineNumberReader.readLine() + newLine;
        } catch (IOException e) {
            Assert.shouldNeverReachHere();
        }
    }
    return stackTrace;
}

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

/**
 * Read a script from the provided {@code LineNumberReader}, using the supplied
 * comment prefix and statement separator, and build a {@code String} containing
 * the lines./*from w  w w  . j av a 2s .  c om*/
 * <p>Lines <em>beginning</em> with the comment prefix are excluded from the
 * results; however, line comments anywhere else &mdash; for example, within
 * a statement &mdash; will be included in the results.
 * @param lineNumberReader the {@code LineNumberReader} containing the script
 * to be processed
 * @param commentPrefix the prefix that identifies comments in the SQL script &mdash;
 * typically "--"
 * @param separator the statement separator in the SQL script &mdash; typically ";"
 * @return a {@code String} containing the script lines
 * @throws IOException in case of I/O errors
 */
public static String readScript(LineNumberReader lineNumberReader, @Nullable String commentPrefix,
        @Nullable String separator) throws IOException {

    String currentStatement = lineNumberReader.readLine();
    StringBuilder scriptBuilder = new StringBuilder();
    while (currentStatement != null) {
        if (commentPrefix != null && !currentStatement.startsWith(commentPrefix)) {
            if (scriptBuilder.length() > 0) {
                scriptBuilder.append('\n');
            }
            scriptBuilder.append(currentStatement);
        }
        currentStatement = lineNumberReader.readLine();
    }
    appendSeparatorToScriptIfNecessary(scriptBuilder, separator);
    return scriptBuilder.toString();
}

From source file:rega.genotype.ui.util.GenotypeLib.java

private static File getTreeEPS(File jobDir, File treeFile)
        throws IOException, InterruptedException, ApplicationException, FileNotFoundException {
    File epsFile = new File(treeFile.getPath().replace(".tre", ".eps"));
    if (epsFile.exists())
        return epsFile;

    Runtime runtime = Runtime.getRuntime();
    Process proc;/*from  ww w . j  a  va2s.c  om*/
    int result;
    String cmd;

    cmd = Settings.treeGraphCommand + " -t " + treeFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);

    InputStream inputStream = proc.getInputStream();

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(inputStream));

    Pattern taxaCountPattern = Pattern.compile("(\\d+) taxa read.");

    int taxa = 0;
    for (;;) {
        String s = reader.readLine();
        if (s == null)
            break;
        Matcher m = taxaCountPattern.matcher(s);

        if (m.find()) {
            taxa = Integer.valueOf(m.group(1)).intValue();
        }
    }

    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    File tgfFile = new File(treeFile.getPath().replace(".tre", ".tgf"));
    File resizedTgfFile = new File(treeFile.getPath().replace(".tre", ".resized.tgf"));

    BufferedReader in = new BufferedReader(new FileReader(tgfFile));
    PrintStream out = new PrintStream(new FileOutputStream(resizedTgfFile));
    String line;
    while ((line = in.readLine()) != null) {
        line = line.replace("\\width{", "%\\width{");
        line = line.replace("\\height{", "%\\height{");
        line = line.replace("\\margin{", "%\\margin{");
        line = line.replace("\\style{r}{plain}", "%\\style{r}{plain}");
        line = line.replace("\\style{default}{plain}", "%\\style{default}{plain}");
        line = line.replaceAll("\\\\len\\{-", "\\\\len\\{");
        out.println(line);

        if (line.equals("\\begindef")) {
            out.println("\\paper{a2}");
            out.println("\\width{170}");
            out.println("\\height{" + (taxa * 8.6) + "}");
            out.println("\\margin{10}{10}{10}{10}");
            out.println("\\style{default}{plain}{13}");
            out.println("\\style{r}{plain}{13}");
        }
    }
    out.close();
    in.close();

    tgfFile.delete();
    resizedTgfFile.renameTo(tgfFile);

    cmd = Settings.treeGraphCommand + " -p " + tgfFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);
    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    return epsFile;
}

From source file:com.puppycrawl.tools.checkstyle.api.Utils.java

/**
 * Loads the contents of a file in a String array using
 * the named charset.//  www.j a v a  2 s .co  m
 * @return the lines in the file
 * @param fileName the name of the file to load
 * @param charsetName the name of a supported charset
 * @throws IOException error occurred
 * @deprecated consider using {@link FileText} instead
 **/
@Deprecated
public static String[] getLines(String fileName, String charsetName) throws IOException {
    final List<String> lines = Lists.newArrayList();
    final FileInputStream fr = new FileInputStream(fileName);
    LineNumberReader lnr = null;
    try {
        lnr = new LineNumberReader(new InputStreamReader(fr, charsetName));
    } catch (final UnsupportedEncodingException ex) {
        fr.close();
        final String message = "unsupported charset: " + ex.getMessage();
        throw new UnsupportedEncodingException(message);
    }
    try {
        while (true) {
            final String l = lnr.readLine();
            if (l == null) {
                break;
            }
            lines.add(l);
        }
    } finally {
        Utils.closeQuietly(lnr);
    }
    return lines.toArray(new String[lines.size()]);
}

From source file:org.opensha.commons.util.FileUtils.java

/**
 * Loads in each line to a text file into an ArrayList ( i.e. a vector ). Each
 * element in the ArrayList represents one line from the file.
 *
 * @param fileName                  File to load in
 * @return                          ArrayList each element one line from the file
 * @throws FileNotFoundException    If the filename doesn't exist
 * @throws IOException              Unable to read from the file
 *//*from   www .jav a2 s. com*/
public static ArrayList<String> loadFile(String fileName, boolean skipBlankLines)
        throws FileNotFoundException, IOException {

    // Debugging
    String S = C + ": loadFile(): ";
    if (D)
        System.out.println(S + "Starting");
    if (D)
        System.out.println(S + fileName);
    // Allocate variables
    ArrayList<String> list = new ArrayList<String>();
    File f = new File(fileName);

    // Read in data if it exists
    if (f.exists()) {

        if (D)
            System.out.println(S + "Found " + fileName + " and loading.");

        boolean ok = true;
        int counter = 0;
        String str;
        FileReader in = new FileReader(fileName);
        LineNumberReader lin = new LineNumberReader(in);

        while (ok) {
            try {
                str = lin.readLine();

                if (str != null) {
                    //omit the blank line
                    if (skipBlankLines && str.trim().equals(""))
                        continue;

                    list.add(str);
                    if (D) {
                        System.out.println(S + counter + ": " + str);
                        counter++;
                    }
                } else
                    ok = false;
            } catch (IOException e) {
                ok = false;
            }
        }
        lin.close();
        in.close();

        if (D)
            System.out.println(S + "Read " + counter + " lines from " + fileName + '.');

    } else if (D)
        System.out.println(S + fileName + " does not exist.");

    // Done
    if (D)
        System.out.println(S + "Ending");
    return list;

}