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:com.aionemu.commons.scripting.AionScriptEngineManager.java

public void executeScriptList(File list) throws IOException {
    if (list.isFile()) {
        LineNumberReader lnr = new LineNumberReader(new FileReader(list));
        String line;/* w  w w.j a  v  a 2  s  . c  o  m*/
        File file;

        while ((line = lnr.readLine()) != null) {
            String[] parts = line.trim().split("#");

            if (parts.length > 0 && !parts[0].startsWith("#") && parts[0].length() > 0) {
                line = parts[0];

                if (line.endsWith("/**")) {
                    line = line.substring(0, line.length() - 3);
                } else if (line.endsWith("/*")) {
                    line = line.substring(0, line.length() - 2);
                }

                file = new File(SCRIPT_FOLDER, line);

                if (file.isDirectory() && parts[0].endsWith("/**")) {
                    this.executeAllScriptsInDirectory(file, true, 32);
                } else if (file.isDirectory() && parts[0].endsWith("/*")) {
                    this.executeAllScriptsInDirectory(file);
                } else if (file.isFile()) {
                    try {
                        this.executeScript(file);
                    } catch (ScriptException e) {
                        reportScriptFileError(file, e);
                    }
                } else {
                    log.warn("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":"
                            + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
                }
            }
        }
        lnr.close();
    } else {
        throw new IllegalArgumentException(
                "Argument must be an file containing a list of scripts to be loaded");
    }
}

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java

public void executeScriptList(File list) throws IOException {
    if (list.isFile()) {
        LineNumberReader lnr = new LineNumberReader(new FileReader(list));
        String line;/*from ww w.  j  av  a 2  s .  c  o  m*/
        File file;

        while ((line = lnr.readLine()) != null) {
            String[] parts = line.trim().split("#");

            if (parts.length > 0 && !parts[0].startsWith("#") && parts[0].length() > 0) {
                line = parts[0];

                if (line.endsWith("/**")) {
                    line = line.substring(0, line.length() - 3);
                } else if (line.endsWith("/*")) {
                    line = line.substring(0, line.length() - 2);
                }

                file = new File(SCRIPT_FOLDER, line);

                if (file.isDirectory() && parts[0].endsWith("/**")) {
                    this.executeAllScriptsInDirectory(file, true, 32);
                } else if (file.isDirectory() && parts[0].endsWith("/*")) {
                    this.executeAllScriptsInDirectory(file);
                } else if (file.isFile()) {
                    try {
                        this.executeScript(file);
                    } catch (ScriptException e) {
                        reportScriptFileError(file, e);
                    }
                } else {
                    _log.warn("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":"
                            + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
                }
            }
        }
        lnr.close();
    } else {
        throw new IllegalArgumentException(
                "Argument must be an file containing a list of scripts to be loaded");
    }
}

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();// w  w w  .ja  v a2  s  . c o  m
        sb.append(line);
        sb.append("\n");
    }
    lnr.close();
    return sb.toString();
}

From source file:com.l2jfree.gameserver.handler.admincommands.AdminTeleport.java

private void bookmark(L2Player activeChar, String Name) {
    File file = new File(Config.DATAPACK_ROOT, "data/html/admin/tele/bookmark.txt");
    LineNumberReader lnr = null;
    String bookmarks = "";
    String table = "";
    try {//from   w w  w  . j av  a 2 s.  c  o m
        String line = null;
        lnr = new LineNumberReader(new FileReader(file));
        while ((line = lnr.readLine()) != null) {
            bookmarks += line + "\n";
            StringTokenizer st = new StringTokenizer(line, ";");
            String nm = st.nextToken();
            table += ("<a action=\"bypass -h admin_move_to " + st.nextToken() + " " + st.nextToken() + " "
                    + st.nextToken() + "\">" + nm + "</a>&nbsp;");
            table += ("<a action=\"bypass -h admin_delbookmark " + nm
                    + "\"><font color=\"FF0000\">[X]</font></a><br>");
        }
        if (Name == null) {
            NpcHtmlMessage adminReply = new NpcHtmlMessage(5);
            adminReply.setFile("data/html/admin/tele/bookmarks.htm");
            adminReply.replace("%bookmarks%", table);
            activeChar.sendPacket(adminReply);
        } else {
            FileWriter save = new FileWriter(file);
            bookmarks += Name + ";" + activeChar.getX() + ";" + activeChar.getY() + ";" + activeChar.getZ()
                    + "\n";
            save.write(bookmarks);
            save.close();
            bookmark(activeChar, null);
        }
    } catch (FileNotFoundException e) {
        activeChar.sendMessage("bookmark.txt not found");
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        try {
            if (lnr != null)
                lnr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:hobby.wei.c.phone.Network.java

public static String PING(String host, boolean format) {
    final int PACKAGES = 4;
    String info = null;/*ww  w  .j av a 2 s . c  o m*/
    String print = null;
    Process process = null;
    LineNumberReader reader = null;
    try {
        final String CMD = "ping -c " + PACKAGES + " " + host;
        if (format) {
            info = "ping-c" + PACKAGES + "-" + host.replace('.', '_');
        } else {
            print = CMD + "\n";
        }

        process = Runtime.getRuntime().exec(CMD);
        reader = new LineNumberReader(new InputStreamReader(process.getInputStream()));

        String line = null;
        boolean start = false;
        int index = -1;
        while ((line = reader.readLine()) != null) {
            if (!format) {
                print += line + "\n";
            } else {
                line = line.trim();
                if (line.toLowerCase().startsWith("ping")) {
                    line = line.substring(0, line.indexOf(')'));
                    line = line.replace("(", "");
                    line = line.replace(' ', '-');
                    line = line.replace('.', '_');
                    start = true;
                } else if (start) {
                    index = line.indexOf(':');
                    if (index > 0) {
                        //?ttl=53
                        line = line.substring(index + 1).trim();
                        index = line.indexOf(' ');
                        line = line.substring(index + 1, line.indexOf(' ', index + 3)).trim();
                        line = line.replace('=', '_');
                        start = false;
                    } else {
                        start = false;
                        continue;
                    }
                } else if (line.startsWith("" + PACKAGES)) {
                    index = line.indexOf(',');
                    line = line.substring(index + 1).trim();
                    line = line.substring(0, line.indexOf(' ')).trim();
                    line = line + "in" + PACKAGES + "received";
                } else if (line.startsWith("rtt")) {
                    line = line.replaceFirst(" ", "-");
                    line = line.replace(" ", "");
                    line = line.replace('/', '-');
                    line = line.replace('.', '_');
                    line = line.replace("=", "--");
                } else {
                    continue;
                }
                if (info == null)
                    info = line;
                info += "--" + line;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null)
                reader.close();
            if (process != null)
                process.destroy(); //??
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }
    return format ? info : print;
}

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  www. ja  v a 2  s . c o  m
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:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * Find Lines Containing passed in match String from the passed in file
 * @param filePath file Path/*from w w  w  .ja va 2s  .  c  o m*/
 * @param findMe find String
 * @return List of Matching Strings
 */
public static List<String> getLinesWithStringsInFile(String filePath, String findMe) {
    LineNumberReader lineReader = null;
    List<String> passwordLineList = null;
    try {
        lineReader = new LineNumberReader(new FileReader(filePath));
        String line = null;
        passwordLineList = new ArrayList<String>();
        while ((line = lineReader.readLine()) != null) {
            if (line.contains(findMe)) {
                passwordLineList.add(line);
            }
        }

    } catch (FileNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            if (lineReader != null)
                lineReader.close();
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    return passwordLineList;
}

From source file:org.opencms.synchronize.CmsSynchronize.java

/**
 * Reads the synchronization list from the last sync process form the file
 * system and stores the information in a HashMap. <p>
 * //from   w  w w .ja v  a 2  s.co m
 * Filenames are stored as keys, CmsSynchronizeList objects as values.
 * @return HashMap with synchronization information of the last sync process
 * @throws CmsException if something goes wrong
 */
private HashMap readSyncList() throws CmsException {

    HashMap syncList = new HashMap();

    // the sync list file in the server fs
    File syncListFile;
    syncListFile = new File(m_destinationPathInRfs, SYNCLIST_FILENAME);
    // try to read the sync list file if it is there
    if (syncListFile.exists()) {
        // prepare the streams to write the data
        FileReader fIn = null;
        LineNumberReader lIn = null;
        try {
            fIn = new FileReader(syncListFile);
            lIn = new LineNumberReader(fIn);
            // read one line from the file
            String line = lIn.readLine();
            while (line != null) {
                line = lIn.readLine();
                // extract the data and create a CmsSychroizedList object
                //  from it
                if (line != null) {
                    StringTokenizer tok = new StringTokenizer(line, ":");
                    String resName = tok.nextToken();
                    String tranResName = tok.nextToken();
                    long modifiedVfs = new Long(tok.nextToken()).longValue();
                    long modifiedFs = new Long(tok.nextToken()).longValue();
                    CmsSynchronizeList sync = new CmsSynchronizeList(resName, tranResName, modifiedVfs,
                            modifiedFs);
                    syncList.put(translate(resName), sync);
                }
            }
        } catch (IOException e) {
            throw new CmsSynchronizeException(Messages.get().container(Messages.ERR_READ_SYNC_LIST_0), e);
        } finally {
            // close all streams that were used
            try {
                if (lIn != null) {
                    lIn.close();
                }
                if (fIn != null) {
                    fIn.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return syncList;
}

From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.db.impl.DbFromFileExtractServiceImpl.java

private Catalog getCatalog(InputStream input) {
    LineNumberReader br = new LineNumberReader(new InputStreamReader(input));
    boolean isTable = false, isColumn = false, isProcedure = false, isTrigger = false;
    String line;//from w  w w.  j a  v  a  2  s. co  m
    try {
        while ((line = br.readLine()) != null) {
            if (line.startsWith(TABLE_FLAG)) {
                // 
                isTable = true;
                isColumn = false;
                isProcedure = false;
                isTrigger = false;
                // 
                continue;
            } else if (line.startsWith(COLUMN_FLAG)) {
                // 
                isColumn = true;
                isTable = false;
                isProcedure = false;
                isTrigger = false;
                // 
                continue;
            } else if (line.startsWith(PROCEDURE_FLAG)) {
                // 
                isProcedure = true;
                isTable = false;
                isColumn = false;
                isTrigger = false;
                // 
                continue;
            } else if (line.startsWith(TRIGGER_FLAG)) {
                // ?
                isTrigger = true;
                isTable = false;
                isColumn = false;
                isProcedure = false;
                // 
                continue;
            }

            if (isColumn) {
                // ?COLUMN-->??,
                genColumn(line);
            } else if (isTable) {
                // ?TABLEVIEW
                genTable(line);
            } else if (isProcedure) {
                // ?PROCEUDRE
                genProcedure(line);
            } else if (isTrigger) {
                // ?TRIGGER
                genTrigger(line);
            }
        }

        return genCatalog();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // ?
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        schemaCache.clear();
        columnSetCache.clear();
    }
    return null;
}

From source file:com.thoughtworks.go.server.database.MigrateHsqldbToH2.java

private void replayScript(File scriptFile) throws SQLException, IOException {
    if (!scriptFile.exists()) {
        return;//  ww  w . j a  v a2 s.  co m
    }

    System.out.println("Migrating hsql file: " + scriptFile.getName());
    Connection con = source.getConnection();
    Statement stmt = con.createStatement();
    stmt.executeUpdate("SET REFERENTIAL_INTEGRITY FALSE");
    LineNumberReader reader = new LineNumberReader(new FileReader(scriptFile));
    String line;
    while ((line = reader.readLine()) != null) {
        try {
            String table = null;
            Matcher matcher = createTable.matcher(line);
            if (matcher.find()) {
                table = matcher.group(2).trim();
            }

            if (line.equals("CREATE SCHEMA PUBLIC AUTHORIZATION DBA")) {
                continue;
            }
            if (line.equals("CREATE SCHEMA CRUISE AUTHORIZATION DBA")) {
                continue;
            }
            if (line.startsWith("CREATE USER SA PASSWORD")) {
                continue;
            }
            if (line.contains("BUILDEVENT VARCHAR(255)")) {
                line = line.replace("BUILDEVENT VARCHAR(255)", "BUILDEVENT LONGVARCHAR");
            }
            if (line.contains("COMMENT VARCHAR(4000)")) {
                line = line.replace("COMMENT VARCHAR(4000)", "COMMENT LONGVARCHAR");
            }
            if (line.contains("CREATE MEMORY TABLE")) {
                line = line.replace("CREATE MEMORY TABLE", "CREATE CACHED TABLE");
            }
            if (table != null && table.equals("MATERIALPROPERTIES") && line.contains("VALUE VARCHAR(255),")) {
                line = line.replace("VALUE VARCHAR(255),", "VALUE LONGVARCHAR,");
            }
            if (line.startsWith("GRANT DBA TO SA")) {
                continue;
            }
            if (line.startsWith("CONNECT USER")) {
                continue;
            }
            if (line.contains("DISCONNECT")) {
                continue;
            }
            if (line.contains("AUTOCOMMIT")) {
                continue;
            }
            stmt.executeUpdate(line);
            if (reader.getLineNumber() % LINES_PER_DOT == 0) {
                System.out.print(".");
                System.out.flush();
            }
            if (reader.getLineNumber() % (80 * LINES_PER_DOT) == 0) {
                System.out.println();
            }

        } catch (SQLException e) {
            bomb("Error executing : " + line, e);
        }
    }
    stmt.executeUpdate("SET REFERENTIAL_INTEGRITY TRUE");
    stmt.executeUpdate("CHECKPOINT SYNC");
    System.out.println("\nDone.");
    reader.close();
    stmt.close();
    con.close();
}