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:net.sf.ginp.browser.FolderManagerImpl.java

/**
 *  Gets the picturesInDirectory attribute of the PicCollection object.
 *
 *@param  relPath  Description of the Parameter
 *@return          The picturesInDirectory value
 *///  ww w. j av a  2s .  c om
private String[] getPicturesInDirectory(final String root, final String relPath) {
    long duration = System.currentTimeMillis() - picCacheTimeout;

    if ((picCacheTimeout < 0) || (duration > MAX_CACHE)) {
        synchronized (picCache) {
            //Clearing a cache while doing a get can
            //cause hashmap to hang.  Hence all the synchronized blocks
            picCacheTimeout = System.currentTimeMillis();
            picCache.clear();
        }
    }

    synchronized (picCache) {
        if (picCache.get(root + relPath) != null) {
            String[] cached = (String[]) picCache.get(root + relPath);

            return cached;
        }
    }

    Vector pics = new Vector();

    try {
        File dir = new File(root + relPath);

        if (dir.isDirectory()) {
            String[] files = dir.list();

            for (int i = 0; i < files.length; i++) {
                File file = new File(root + relPath + "/" + files[i]);

                if ((!file.isDirectory()) && ((files[i].toLowerCase()).endsWith(".jpg")
                        || (files[i].toLowerCase()).endsWith(".jpeg"))) {
                    pics.add(files[i]);

                    if (log.isDebugEnabled()) {
                        log.debug("Adding picture file: " + files[i]);
                    }
                }
            }

            // Add Featured Pics
            File fl = new File(root + relPath + "ginpfolder.xml");

            if (fl.exists()) {
                FileReader fr = new FileReader(fl);
                LineNumberReader lr = new LineNumberReader(fr);
                StringBuffer sb = new StringBuffer();
                String temp;

                while ((temp = lr.readLine()) != null) {
                    sb.append(temp + "\n");
                }

                String featuredpicsXML = StringTool.getXMLTagContent("featuredpics", sb.toString());
                String[] picsXML = StringTool.splitToArray(featuredpicsXML, "<pic>");

                for (int i = 0; i < picsXML.length; i++) {
                    if (picsXML[i].indexOf("</pic>") != -1) {
                        temp = picsXML[i].substring(0, picsXML[i].indexOf("</pic>"));
                        fl = new File(root + relPath + temp);

                        if (fl.exists()) {
                            pics.add(temp);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        log.error(ex);
    }

    String[] retPictures = new String[pics.size()];

    for (int i = 0; i < pics.size(); i++) {
        retPictures[i] = (String) pics.get(i);
    }

    String[] sorted = sortPictures(retPictures);

    synchronized (picCache) {
        if (picCache.get(root + relPath) == null) {
            picCache.put(root + relPath, sorted);
        } else {
            return (String[]) picCache.get(root + relPath);
        }
    }

    // Only One Thread Per Directory Should Ever Get Here
    // (Unless it takes longer than 2 minutes to make)
    synchronized (MakeThumbs.class) {
        if ((mth == null) || ((mthThread != null) && !mthThread.isAlive())) {
            mth = new MakeThumbs();
            mthThread = new Thread(mth);
            mthThread.setDaemon(true);
            mthThread.setPriority(Thread.MIN_PRIORITY);
            mthThread.start();
        }
    }

    mth.addToQueue(root + relPath, sorted);

    return sorted;
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void recover(final File file) {
    LineNumberReader reader = null;
    try {//  w w w . j  a va2 s. co m
        reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), Util.ENCODING));

        while (true) {
            final String line = reader.readLine();
            if (line == null) {
                break;
            }
            if (!line.startsWith("#transaction started")) {
                throw new NoSqlStoreException(
                        "No transaction start found: " + line + " (" + reader.getLineNumber() + ")");
            }
            readTransaction(reader);
        }
    } catch (final IOException e) {
        throw new NoSqlStoreException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                throw new NoSqlStoreException(e);
            }
        }
    }
}

From source file:org.fbk.cit.hlt.dirha.Evaluator.java

private Map<Integer, Sentence> read(File fin) throws IOException {
    LineNumberReader lr = new LineNumberReader(new InputStreamReader(new FileInputStream(fin), "UTF-8"));

    String line = null;/*from   w  w  w.j a  v  a 2s .  c  o m*/
    Map<Integer, Sentence> sentenceMap = new HashMap<>();
    String sid = null;
    int count = 0;
    Sentence sentence = null;
    while ((line = lr.readLine()) != null) {

        String[] s = line.split("\t", -1);
        if (s.length > 5) {

            if (sid == null) {
                sid = s[0];
                sentence = new Sentence(sid);
            }
            if (!s[0].equalsIgnoreCase(sid)) {
                sentenceMap.put(Integer.parseInt(sid), sentence);
                sid = s[0];
                sentence = new Sentence(sid);
            }
            if (!s[6].trim().equalsIgnoreCase("O")) {
                ClassifierResults res = ClassifierResults.fromTSV(s, 2);
                sentence.add(s[0], res.getFrame(), res.getRole(), res.getToken().replace(" ", ""));
            }

        }

    }
    sentenceMap.put(Integer.parseInt(sid), sentence);
    return sentenceMap;
}

From source file:org.apache.isis.objectstore.nosql.db.file.server.FileServer.java

private void readTransaction(final LineNumberReader reader) throws IOException {
    final ArrayList<FileContent> files = new ArrayList<FileContent>();
    final DataFileWriter content = new DataFileWriter(files);
    String header;/*from   w ww . j av a 2 s. c o m*/
    while ((header = reader.readLine()) != null) {
        if (header.startsWith("#transaction ended")) {
            LOG.debug("transaction read in (ending " + reader.getLineNumber() + ")");
            content.writeData();
            reader.readLine();
            return;
        }
        if (header.startsWith("S")) {
            final String[] split = header.substring(1).split(" ");
            final String key = split[0];
            final String name = split[1];
            server.saveService(key, name);
            reader.readLine();
        } else if (header.startsWith("B")) {
            final String[] split = header.substring(1).split(" ");
            final String name = split[0];
            final long nextBatch = Long.valueOf(split[1]);
            server.saveNextBatch(name, nextBatch);
            reader.readLine();
        } else {
            FileContent elementData;
            elementData = readElementData(header, reader);
            files.add(elementData);
        }
    }
    LOG.warn("transaction has no ending marker so is incomplete and will not be restored (ending "
            + reader.getLineNumber() + ")");
}

From source file:com.l2jfree.gameserver.instancemanager.leaderboards.FishermanManager.java

public void engineInit() {
    _ranks = new FastMap<Integer, FishRank>();
    String line = null;// w  w w . j a va2 s. c  om
    LineNumberReader lnr = null;
    String lineId = "";
    FishRank rank = null;
    File file = new File(Config.DATAPACK_ROOT, "data/fish.dat");

    try {
        boolean created = file.createNewFile();
        if (created)
            _log.info("FishManager: fish.dat was not existing and has been created.");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            lnr = new LineNumberReader(new BufferedReader(new FileReader(file)));
            while ((line = lnr.readLine()) != null) {
                if (line.trim().length() == 0 || line.startsWith("#"))
                    continue;

                lineId = line;
                line = line.replaceAll(" ", "");

                String t[] = line.split(":");

                int owner = Integer.parseInt(t[0]);
                rank = new FishRank();

                rank.cought = Integer.parseInt(t[1].split("-")[0]);
                rank.escaped = Integer.parseInt(t[1].split("-")[1]);

                rank.name = t[2];

                _ranks.put(owner, rank);
            }
        } catch (Exception e) {
            _log.warn("FishManager.engineInit() >> last line parsed is \n[" + lineId + "]\n", e);
        } finally {
            IOUtils.closeQuietly(lnr);
        }

        startSaveTask();
        _log.info("FishManager: Loaded " + _ranks.size() + " player(s).");
    }
}

From source file:com.l2jfree.gameserver.instancemanager.leaderboards.ArenaManager.java

public void engineInit() {
    _ranks = new FastMap<Integer, ArenaRank>();
    String line = null;//from w w w.  j av a  2 s.  co  m
    LineNumberReader lnr = null;
    String lineId = "";
    ArenaRank rank = null;
    File file = new File(Config.DATAPACK_ROOT, "data/arena.dat");

    try {
        boolean created = file.createNewFile();
        if (created)
            _log.info("ArenaManager: arena.dat was not existing and has been created.");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            lnr = new LineNumberReader(new BufferedReader(new FileReader(file)));
            while ((line = lnr.readLine()) != null) {
                if (line.trim().length() == 0 || line.startsWith("#"))
                    continue;

                lineId = line;
                line = line.replaceAll(" ", "");

                String t[] = line.split(":");

                int owner = Integer.parseInt(t[0]);
                rank = new ArenaRank();

                rank.kills = Integer.parseInt(t[1].split("-")[0]);
                rank.death = Integer.parseInt(t[1].split("-")[1]);

                rank.name = t[2];

                _ranks.put(owner, rank);
            }
        } catch (Exception e) {
            _log.warn("ArenaManager.engineInit() >> last line parsed is \n[" + lineId + "]\n", e);
        } finally {
            IOUtils.closeQuietly(lnr);
        }

        startSaveTask();
        _log.info("ArenaManager: Loaded " + _ranks.size() + " player(s).");
    }
}

From source file:org.jboss.as.test.integration.domain.suites.ResponseStreamTestCase.java

private void readLogStream(InputStream stream, boolean forServer, boolean forMaster) throws IOException {

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(stream, StandardCharsets.UTF_8));

    String expected = LogStreamExtension.getLogMessage(logMessageContent);
    boolean readRegisteredServer = false;
    boolean readRegisteredSlave = false;
    boolean readExpected = false;
    String read;/*from ww  w.  j a v  a2 s  .co m*/
    while ((read = reader.readLine()) != null) {
        readRegisteredServer = readRegisteredServer || read.contains("WFLYHC0020");
        readRegisteredSlave = readRegisteredSlave || read.contains("WFLYHC0019");
        readExpected = readExpected || read.contains(expected);
    }

    if (forServer) {
        Assert.assertFalse(readRegisteredServer);
    } else if (forMaster) {
        Assert.assertTrue(readRegisteredSlave);
    } else {
        Assert.assertFalse(readRegisteredSlave);
        Assert.assertTrue(readRegisteredServer);
    }
    Assert.assertTrue(readExpected);

    reader.close();

}

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.//from w w w.j  ava2  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.apache.pdfbox.text.TestTextStripper.java

/**
 * Validate text extraction on a single file.
 *
 * @param inFile The PDF file to validate
 * @param outDir The directory to store the output in
 * @param bLogResult Whether to log the extracted text
 * @param bSort Whether or not the extracted text is sorted
 * @throws Exception when there is an exception
 *//*from w w w  . j a va2s. com*/
public void doTestFile(File inFile, File outDir, boolean bLogResult, boolean bSort) throws Exception {
    if (bSort) {
        log.info("Preparing to parse " + inFile.getName() + " for sorted test");
    } else {
        log.info("Preparing to parse " + inFile.getName() + " for standard test");
    }

    if (!outDir.exists()) {
        if (!outDir.mkdirs()) {
            throw (new Exception("Error creating " + outDir.getAbsolutePath() + " directory"));
        }
    }

    //System.out.println("  " + inFile + (bSort ? " (sorted)" : ""));
    PDDocument document = PDDocument.load(inFile);
    try {
        File outFile;
        File diffFile;
        File expectedFile;

        if (bSort) {
            outFile = new File(outDir, inFile.getName() + "-sorted.txt");
            diffFile = new File(outDir, inFile.getName() + "-sorted-diff.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + "-sorted.txt");
        } else {
            outFile = new File(outDir, inFile.getName() + ".txt");
            diffFile = new File(outDir, inFile.getName() + "-diff.txt");
            expectedFile = new File(inFile.getParentFile(), inFile.getName() + ".txt");
        }

        // delete possible leftover
        diffFile.delete();

        OutputStream os = new FileOutputStream(outFile);
        try {
            os.write(0xEF);
            os.write(0xBB);
            os.write(0xBF);

            Writer writer = new BufferedWriter(new OutputStreamWriter(os, ENCODING));
            try {
                //Allows for sorted tests 
                stripper.setSortByPosition(bSort);
                stripper.writeText(document, writer);
            } finally {
                // close the written file before reading it again
                writer.close();
            }
        } finally {
            os.close();
        }

        if (bLogResult) {
            log.info("Text for " + inFile.getName() + ":");
            log.info(stripper.getText(document));
        }

        if (!expectedFile.exists()) {
            this.bFail = true;
            log.error("FAILURE: Input verification file: " + expectedFile.getAbsolutePath() + " did not exist");
            return;
        }

        boolean localFail = false;

        LineNumberReader expectedReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(expectedFile), ENCODING));
        LineNumberReader actualReader = new LineNumberReader(
                new InputStreamReader(new FileInputStream(outFile), ENCODING));

        while (true) {
            String expectedLine = expectedReader.readLine();
            while (expectedLine != null && expectedLine.trim().length() == 0) {
                expectedLine = expectedReader.readLine();
            }
            String actualLine = actualReader.readLine();
            while (actualLine != null && actualLine.trim().length() == 0) {
                actualLine = actualReader.readLine();
            }
            if (!stringsEqual(expectedLine, actualLine)) {
                this.bFail = true;
                localFail = true;
                log.error("FAILURE: Line mismatch for file " + inFile.getName() + " (sort = " + bSort + ")"
                        + " at expected line: " + expectedReader.getLineNumber() + " at actual line: "
                        + actualReader.getLineNumber() + "\nexpected line was: \"" + expectedLine + "\""
                        + "\nactual line was:   \"" + actualLine + "\"" + "\n");

                //lets report all lines, even though this might produce some verbose logging
                //break;
            }

            if (expectedLine == null || actualLine == null) {
                break;
            }
        }
        expectedReader.close();
        actualReader.close();
        if (!localFail) {
            outFile.delete();
        } else {
            // https://code.google.com/p/java-diff-utils/wiki/SampleUsage
            List<String> original = fileToLines(expectedFile);
            List<String> revised = fileToLines(outFile);

            // Compute diff. Get the Patch object. Patch is the container for computed deltas.
            Patch patch = DiffUtils.diff(original, revised);

            PrintStream diffPS = new PrintStream(diffFile, ENCODING);
            for (Object delta : patch.getDeltas()) {
                if (delta instanceof ChangeDelta) {
                    ChangeDelta cdelta = (ChangeDelta) delta;
                    diffPS.println("Org: " + cdelta.getOriginal());
                    diffPS.println("New: " + cdelta.getRevised());
                    diffPS.println();
                } else if (delta instanceof DeleteDelta) {
                    DeleteDelta ddelta = (DeleteDelta) delta;
                    diffPS.println("Org: " + ddelta.getOriginal());
                    diffPS.println("New: " + ddelta.getRevised());
                    diffPS.println();
                } else if (delta instanceof InsertDelta) {
                    InsertDelta idelta = (InsertDelta) delta;
                    diffPS.println("Org: " + idelta.getOriginal());
                    diffPS.println("New: " + idelta.getRevised());
                    diffPS.println();
                } else {
                    diffPS.println(delta);
                }
            }
            diffPS.close();
        }
    } finally {
        document.close();
    }
}

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
 * //from w ww .  ja  v  a2 s.co 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;
}