Example usage for java.io FileReader close

List of usage examples for java.io FileReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:ffx.potential.parsers.XYZFileFilter.java

/**
 * <p>/*  w  w  w . j  a  v a 2  s  .  c  o m*/
 * acceptDeep</p>
 *
 * @param file a {@link java.io.File} object.
 * @return a boolean.
 */
public boolean acceptDeep(File file) {
    try {
        if (file == null || file.isDirectory() || !file.canRead()) {
            return false;
        }
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        if (!br.ready()) {
            return false;
        }
        /**
         * If the first token is not an integer this file is not a TINKER
         * Cartesian Coordinate File.
         */
        String rawdata = br.readLine();
        String header[] = rawdata.trim().split(" +");
        if (header == null || header.length == 0) {
            return false;
        }
        try {
            Integer.parseInt(header[0]);
        } catch (Exception e) {
            return false;
        }
        /**
         * If the the first Atom line does not begin with an integer and
         * contain at least six tokens, this is not a TINKER cartesian
         * coordinate file.
         *
         */
        String firstAtom = br.readLine();
        if (firstAtom == null) {
            return false;
        }
        br.close();
        fr.close();
        String data[] = firstAtom.trim().split(" +");
        if (data == null || data.length < 6) {
            return false;
        }
        try {
            Integer.parseInt(data[0]);
        } catch (Exception e) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return true;
    }
}

From source file:org.apache.hadoop.yarn.util.SmapsBasedProcessTree.java

/**
 * Construct the ProcessInfo using the process' PID and procfs rooted at the
 * specified directory and return the same. It is provided mainly to assist
 * testing purposes.//from w  w  w  .  jav a 2  s . c  om
 * 
 * Returns null on failing to read from procfs,
 * 
 * @param pinfo
 *          ProcessInfo that needs to be updated
 * @param procfsDir
 *          root of the proc file system
 * @return updated ProcessInfo, null on errors.
 */
private static ProcessInfo constructProcessInfo(ProcessInfo pinfo, String procfsDir) {
    ProcessInfo ret = null;
    // Read "procfsDir/<pid>/stat" file - typically /proc/<pid>/stat
    BufferedReader in = null;
    FileReader fReader = null;
    try {
        File pidDir = new File(procfsDir, pinfo.getPid());
        fReader = new FileReader(new File(pidDir, PROCFS_STAT_FILE));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // The process vanished in the interim!
        return ret;
    }

    ret = pinfo;
    try {
        String str = in.readLine(); // only one line
        Matcher m = PROCFS_STAT_FILE_FORMAT.matcher(str);
        boolean mat = m.find();
        if (mat) {
            // Set (name) (ppid) (pgrpId) (session) (utime) (stime) (vsize) (rss)
            pinfo.updateProcessInfo(m.group(2), m.group(3), Integer.parseInt(m.group(4)),
                    Integer.parseInt(m.group(5)), Long.parseLong(m.group(7)), new BigInteger(m.group(8)),
                    Long.parseLong(m.group(10)), Long.parseLong(m.group(11)));
        } else {
            LOG.warn("Unexpected: procfs stat file is not in the expected format" + " for process with pid "
                    + pinfo.getPid());
            ret = null;
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
        ret = null;
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }

    return ret;
}

From source file:ffx.potential.parsers.XYZFilter.java

/**
 * <p>//  w w w . jav a 2  s .  c  o  m
 * readOnto</p>
 *
 * @param newFile a {@link java.io.File} object.
 * @param oldSystem a {@link ffx.potential.MolecularAssembly} object.
 * @return a boolean.
 */
public static boolean readOnto(File newFile, MolecularAssembly oldSystem) {
    if (newFile == null || !newFile.exists() || oldSystem == null) {
        return false;
    }
    try {
        FileReader fr = new FileReader(newFile);
        BufferedReader br = new BufferedReader(fr);
        String data = br.readLine();
        if (data == null) {
            return false;
        }
        String tokens[] = data.trim().split(" +");
        int num_atoms = Integer.parseInt(tokens[0]);
        if (num_atoms != oldSystem.getAtomList().size()) {
            return false;
        }
        double d[][] = new double[num_atoms][3];
        for (int i = 0; i < num_atoms; i++) {
            if (!br.ready()) {
                return false;
            }
            data = br.readLine();
            if (data == null) {
                logger.warning("Check atom " + (i + 1));
                return false;
            }
            tokens = data.trim().split(" +");
            if (tokens == null || tokens.length < 6) {
                logger.warning("Check atom " + (i + 1));
                return false;
            }
            d[i][0] = Double.parseDouble(tokens[2]);
            d[i][1] = Double.parseDouble(tokens[3]);
            d[i][2] = Double.parseDouble(tokens[4]);
        }
        ArrayList<Atom> atoms = oldSystem.getAtomList();
        for (Atom a : atoms) {
            int index = a.getXYZIndex() - 1;
            a.setXYZ(d[index]);
        }
        oldSystem.center();
        oldSystem.setFile(newFile);
        br.close();
        fr.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.x460dot10.b.registrar.StartupManager.java

/**
 * Imports data/passwords.txt into <code>University.passwords</code>
 *
 * @return             Indicates import of passwords was successful
 * @throws IOException //  w  ww .ja v  a2 s.c  o  m
 */
public boolean importPasswords() throws IOException {
    Boolean importPasswordsSuccessful = true;
    File file = new File("data/mockpasswords.dat");
    FileReader reader = null;
    Object nextPassword;
    ArrayList<Password> filePasswords = new ArrayList<Password>();
    try {
        reader = new FileReader(file);
        CSVFormat format = CSVFormat.DEFAULT;
        List<CSVRecord> records = new CSVParser(reader, format).getRecords();

        for (CSVRecord record : records) {
            String idAsString = record.values[0];
            Integer id = Integer.parseInt(idAsString);
            String userName = record.values[1];
            String password = record.values[2];
            nextPassword = Password.getStaticInstance(id, userName, password).clone();
            filePasswords.add((Password) nextPassword);
        }
        uni.passwordManager.importPasswords(filePasswords);
    } catch (Exception ex) {
        // TODO send error message to a log file
        System.err.println("Error: " + ex.getMessage());
        importPasswordsSuccessful = false;
    } finally {
        if (reader != null)
            reader.close();
    }
    return importPasswordsSuccessful;
}

From source file:jdao.JDAO.java

public static DataSource createDatasourceFromFile(File file) {
    try {//w  w  w  .j a  va  2s.  co  m
        Properties properties = new Properties();
        FileReader fh = new FileReader(file);
        properties.load(fh);
        fh.close();

        DataSource dataSource = null;
        dataSource = createDataSourceByProperties(file, dataSource, properties);

        return dataSource;
    } catch (Exception xe) {
        log("Error processing datasource: " + file, xe);
    }
    return null;
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

private void loadLatestServerInfo() {
    Document xmlResponse;/*from  w w  w. j  a v  a  2s .c om*/
    File file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf", "server-update.xml");
    if (!file.exists()) {
        return;
    }
    // Check read privs.
    if (!file.canRead()) {
        Log.warn("Cannot retrieve server updates. File must be readable: " + file.getName());
        return;
    }
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlResponse = xmlReader.read(reader);
    } catch (Exception e) {
        Log.error("Error reading server-update.xml", e);
        return;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                // Do nothing
            }
        }
    }
    // Parse info and recreate update information (if still required)
    Element openfire = xmlResponse.getRootElement().element("openfire");
    if (openfire != null) {
        Version latestVersion = new Version(openfire.attributeValue("latest"));
        String changelog = openfire.attributeValue("changelog");
        String url = openfire.attributeValue("url");
        // Check if current server version is correct
        Version currentServerVersion = XMPPServer.getInstance().getServerInfo().getVersion();
        if (latestVersion.isNewerThan(currentServerVersion)) {
            serverUpdate = new Update("Openfire", latestVersion.getVersionString(), changelog, url);
        }
    }
}

From source file:org.jivesoftware.openfire.update.UpdateManager.java

private void loadAvailablePluginsInfo() {
    Document xmlResponse;//from   w ww . jav  a  2  s  . co m
    File file = new File(JiveGlobals.getHomeDirectory() + File.separator + "conf", "available-plugins.xml");
    if (!file.exists()) {
        return;
    }
    // Check read privs.
    if (!file.canRead()) {
        Log.warn("Cannot retrieve available plugins. File must be readable: " + file.getName());
        return;
    }
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        xmlResponse = xmlReader.read(reader);
    } catch (Exception e) {
        Log.error("Error reading available-plugins.xml", e);
        return;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                // Do nothing
            }
        }
    }
    // Parse info and recreate available plugins
    Iterator it = xmlResponse.getRootElement().elementIterator("plugin");
    while (it.hasNext()) {
        Element plugin = (Element) it.next();
        String pluginName = plugin.attributeValue("name");
        String latestVersion = plugin.attributeValue("latest");
        String icon = plugin.attributeValue("icon");
        String readme = plugin.attributeValue("readme");
        String changelog = plugin.attributeValue("changelog");
        String url = plugin.attributeValue("url");
        String licenseType = plugin.attributeValue("licenseType");
        String description = plugin.attributeValue("description");
        String author = plugin.attributeValue("author");
        String minServerVersion = plugin.attributeValue("minServerVersion");
        String fileSize = plugin.attributeValue("fileSize");
        AvailablePlugin available = new AvailablePlugin(pluginName, description, latestVersion, author, icon,
                changelog, readme, licenseType, minServerVersion, url, fileSize);
        // Add plugin to the list of available plugins at js.org
        availablePlugins.put(pluginName, available);
    }
}

From source file:edu.ur.ir.index.DefaultPlainTextExtractor.java

/**
 * Extract text from the plain text document
 * @throws Exception //  w w w  . java  2 s .  c  o  m
 * 
 * @see edu.ur.ir.index.FileTextExtractor#getText(java.io.File)
 */
public String getText(File f) throws Exception {
    String text = null;
    // don't even try if the file is too large
    if (isFileTooLarge(f)) {
        return text;
    }
    FileReader reader = null;
    StringBuffer sb = new StringBuffer();
    char[] buffer = new char[1024];

    if (f.exists() && f.isFile() && (f.length() > 0)) {
        try {
            reader = new FileReader(f);
            int count = 0;

            while (count != -1) {
                count = reader.read(buffer, 0, bufferSize);
                // write out those same bytes
                if (count > 0) {
                    sb.append(buffer, 0, count);
                }
            }

            if (sb != null && !sb.toString().trim().equals("")) {
                text = sb.toString();
            }
        } catch (OutOfMemoryError oome) {
            text = null;
            log.error("could not extract text", oome);
            throw (oome);
        } catch (Exception e) {
            text = null;
            log.error("could not create document", e);
            throw (e);
        }

        finally {
            if (reader != null) {
                try {
                    reader.close();
                    reader = null;
                } catch (Exception e) {
                    log.error("could not close reader", e);
                    reader = null;
                }
            }
        }

    }

    return text;
}

From source file:com.photon.phresco.util.Utility.java

public static void killProcess(String baseDir, String actionType) throws PhrescoException {
    File do_not_checkin = new File(baseDir + File.separator + DO_NOT_CHECKIN_DIRY);
    File jsonFile = new File(do_not_checkin.getPath() + File.separator + "process.json");
    if (!jsonFile.exists()) {
        return;/*from   w  w  w  .j  a va  2s.  co m*/
    }
    try {
        JSONObject jsonObject = new JSONObject();
        JSONParser parser = new JSONParser();
        FileReader reader = new FileReader(jsonFile);
        jsonObject = (JSONObject) parser.parse(reader);
        Object processId = jsonObject.get(actionType);
        if (processId == null) {
            return;
        }
        if (System.getProperty(Constants.OS_NAME).startsWith(Constants.WINDOWS_PLATFORM)) {
            Runtime.getRuntime().exec("cmd /X /C taskkill /F /T /PID " + processId.toString());
        } else {
            Runtime.getRuntime().exec(Constants.JAVA_UNIX_PROCESS_KILL_CMD + processId.toString());
        }
        jsonObject.remove(actionType);
        FileWriter writer = new FileWriter(jsonFile);
        writer.write(jsonObject.toString());
        writer.close();
        reader.close();
        if (jsonObject.size() <= 0) {
            FileUtil.delete(jsonFile);
        }
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (ParseException e) {
        throw new PhrescoException(e);
    }
}

From source file:com.x460dot10.b.registrar.StartupManager.java

/**
 * Imports data/students.txt into <code>University.students</code>
 *
 * @return             Indicates import of students was successful
 * @throws IOException //from w  w w  . j a v  a  2 s  .  co m
 */
public boolean importStudents() throws IOException {
    Boolean importStudentsSuccessful = true;
    File file = new File("data/mockstudents.dat");
    FileReader reader = null;
    ArrayList<MockStudent> fileStudents = new ArrayList<MockStudent>();
    Object nextStudent;
    try {
        reader = new FileReader(file);
        CSVFormat format = CSVFormat.DEFAULT;
        List<CSVRecord> records = new CSVParser(reader, format).getRecords();

        for (CSVRecord record : records) {
            String idAsString = record.values[0];
            Integer id = Integer.parseInt(idAsString);
            String first = record.values[1];
            String last = record.values[2];
            String dob = record.values[3];
            nextStudent = MockStudent.getStaticInstance(id, first, last, dob).clone();
            fileStudents.add((MockStudent) nextStudent);
        }
        uni.students.addAll(fileStudents);

    } catch (Exception ex) {
        // TODO send error message to a log file
        System.err.println("Error: " + ex.getMessage());
        importStudentsSuccessful = false;
    } finally {
        if (reader != null)
            reader.close();
    }
    return importStudentsSuccessful;
}