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:com.btoddb.chronicle.FileTestUtils.java

public Matcher<File> hasEventsInOrder(final Event[] targetEvents) {
    return new TypeSafeMatcher<File>() {
        String errorDesc;//w  ww.jav a2 s  . c  om
        String expected;
        String got;

        @Override
        protected boolean matchesSafely(final File f) {
            FileReader fr = null;
            try {
                fr = new FileReader(f);
                List<String> lines = IOUtils.readLines(fr);
                if (targetEvents.length != lines.size()) {
                    errorDesc = "number of events: ";
                    expected = "" + targetEvents.length;
                    got = "" + lines.size();
                    return false;
                }

                for (int i = 0; i < targetEvents.length; i++) {
                    Event event = config.getEventSerializer().deserialize(lines.get(i));
                    if (!targetEvents[i].equals(event)) {
                        errorDesc = "event: ";
                        expected = new String(config.getEventSerializer().serialize(targetEvents[i]));
                        got = lines.get(i);
                        return false;
                    }
                }
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } finally {
                if (null != fr) {
                    try {
                        fr.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        @Override
        public void describeTo(final Description description) {
            description.appendText(errorDesc).appendValue(expected);
        }

        @Override
        protected void describeMismatchSafely(final File item, final Description mismatchDescription) {
            mismatchDescription.appendText("  was: ").appendValue(got);
        }
    };
}

From source file:com.cloudera.flume.util.FlumeShell.java

/**
 * Exec the specified filename. This command is called "source" like in bash/c
 * shells/*from w w  w  .ja v  a 2  s . co  m*/
 */
long execFile(String filename) {
    FileReader f = null;
    try {
        f = new FileReader(filename);
    } catch (IOException e) {
        System.out.println("unable to source file " + filename + ": " + e.getMessage());
        return -1;
    }

    BufferedReader in = new BufferedReader(f);
    String str;
    long lastret = 0;
    long lineno = 0;
    try {
        while ((str = in.readLine()) != null) {
            lineno++;
            lastret = executeLine(str);
        }
        return lastret;

    } catch (IOException ioe) {
        System.out.println("Problem reading line " + filename + ":" + lineno + " : " + ioe.getMessage());
        return -1;
    } finally {
        try {
            in.close();
            f.close();
        } catch (IOException e) {
            LOG.error("Unable to close " + f);
        }
    }
}

From source file:org.pentaho.marketplace.domain.services.PluginService.java

private String discoverInstalledVersion(IPlugin plugin) {

    String versionPath = PentahoSystem.getApplicationContext()
            .getSolutionPath("system/" + plugin.getId() + "/version.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    FileReader reader = null;//from  w  ww .  j a  v a  2s  .c  om
    try {
        File file = new File(versionPath);
        if (!file.exists()) {
            return "Unknown";
        }
        DocumentBuilder db = dbf.newDocumentBuilder();
        reader = new FileReader(versionPath);
        Document dom = db.parse(new InputSource(reader));
        NodeList versionElements = dom.getElementsByTagName("version");
        if (versionElements.getLength() >= 1) {
            Element versionElement = (Element) versionElements.item(0);

            plugin.setInstalledBuildId(versionElement.getAttribute("buildId"));
            plugin.setInstalledBranch(versionElement.getAttribute("branch"));
            plugin.setInstalledVersion(versionElement.getTextContent());

            return versionElement.getTextContent();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            // do nothing
        }
    }
    return "Unknown";
}

From source file:org.ala.repository.RepositoryImpl.java

public List<Triple<String, String, String>> readRdfFile(Document doc) {
    List<Triple<String, String, String>> triples = null;
    FileReader reader = null;

    if (doc == null) {
        return null;
    }/*from ww w .  j a  va2  s.  co  m*/

    //get RDF file content and populate uploadItem.
    try {
        String repoLocation = doc.getFilePath();
        File rdfFile = new File(repoLocation + "/rdf");
        reader = new FileReader(rdfFile);
        List<Triple<String, String, String>> rdf = TurtleUtils.readTurtle(reader, false);
        if (rdf != null) {
            triples = new ArrayList<Triple<String, String, String>>();
            for (Triple<String, String, String> triple : rdf) {
                triples.add(new Triple<String, String, String>(MappingUtils.getSubject(), triple.predicate,
                        triple.object));
            }
        }
    } catch (Exception e) {
        log.error("readRdfFile(): " + e.toString());
    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            log.error("readRdfFile(): " + e.toString());
        }
    }
    return triples;
}

From source file:org.apache.sling.its.ITSTest.java

/**
 * Compare file line by line./*from ww  w .j  a  v  a  2  s  .  c o  m*/
 *
 * @param output
 *         The path of the output file. The output file should be the file
 *         modified by Okapi's main.
 * @param gold
 *         The path of the expected file.
 * @return true if output and expected file are the same; otherwise, false.
 */
private boolean compareFilesLineByLine(final String output, final String gold) {
    FileReader outputFileReader = null;
    FileReader expectedFileReader = null;

    BufferedReader outputbr = null;
    BufferedReader expectedbr = null;
    try {
        outputFileReader = new FileReader(output);
        expectedFileReader = new FileReader(gold);

        outputbr = new BufferedReader(outputFileReader);
        expectedbr = new BufferedReader(expectedFileReader);

        String outputText;
        String expectedText;
        while (((outputText = outputbr.readLine()) != null)
                && ((expectedText = expectedbr.readLine()) != null)) {
            if (!StringUtils.equals(outputText, expectedText)) {
                System.out.println("There is a difference between the generated output file,\n" + output
                        + "\nand the expected file,\n" + gold + ".");
                System.out.println("Output text: " + outputText);
                System.out.println("Expected text: " + expectedText);
                return false;
            }
        }
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (final IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (outputFileReader != null) {
            try {
                outputFileReader.close();
            } catch (final IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        if (expectedFileReader != null) {
            try {
                expectedFileReader.close();
            } catch (final IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        if (outputbr != null) {
            try {
                outputbr.close();
            } catch (final IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        if (expectedbr != null) {
            try {
                expectedbr.close();
            } catch (final IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }
    return true;
}

From source file:com.supermap.desktop.icloud.CloudLicenseDialog.java

private void initToken() {
    FileReader reader = null;
    try {/*from  w ww . ja va2s.  c om*/
        File file = new File(TOKEN_PATH);
        if (file.exists()) {
            reader = new FileReader(file);
            char[] charArray = new char[(int) file.length()];
            reader.read(charArray);
            String[] token = String.valueOf(charArray).split(",");
            if (null != token && token.length == 4) {
                boolean savePassword = "true".equalsIgnoreCase(token[SAVE_TOKEN]);
                boolean autoLogin = "true".equalsIgnoreCase(token[AUTO_LOGIN]);
                checkBoxSavePassword.setSelected(savePassword);
                checkBoxAutoLogin.setSelected(autoLogin);
                if (savePassword) {
                    textFieldUserName.setText(token[USER_NAME]);
                    fieldPassWord.setText(token[PASS_WORD]);
                }
                if (autoLogin) {
                    buttonLogin.doClick();
                }
            }
        }

    } catch (FileNotFoundException e) {
        Application.getActiveApplication().getOutput().output(e);
    } catch (IOException e) {
        Application.getActiveApplication().getOutput().output(e);
    } finally {
        try {
            if (null != reader) {
                reader.close();
            }
        } catch (IOException e) {
            Application.getActiveApplication().getOutput().output(e);
        }
    }
}

From source file:org.crawler.LinkExtractor.java

void processFile(File jsonFile) throws Exception {

    System.out.println("Processing JSON file " + jsonFile.getName());

    FileReader fr = new FileReader(jsonFile);
    BufferedReader br = new BufferedReader(fr);
    String line;/*  w ww  . j a v a2  s. co  m*/
    StringBuffer buff = new StringBuffer();

    while ((line = br.readLine()) != null) {
        buff.append(line + "\n");
    }

    JSONObject jsonObject = new JSONObject(buff.toString());
    JSONArray items = (JSONArray) jsonObject.get("items");
    JSONObject item;
    Question question = null;

    for (int i = 0; i < items.length(); i++) {
        question = null;

        try {
            item = items.getJSONObject(i);
            question = new Question(item); // the current question
            int qid = question.getID();
            // Skip if the linked questions for this one
            // has already been crawled                
            if (crawledLinks.get(qid) != null) {
                System.out.println("Skipping crawling of question: " + qid);
                continue;
            }

            String links = extractLinkedIds(question);
            numRequests++;
            if (numRequests == 10000) {
                System.out.println("Breaking after 10000 requests");
            }

            String linkMsg = qid + "\t" + links;
            fout.write(linkMsg + "\n");

            System.out.println(linkMsg);
            Thread.sleep(delay);
        } catch (Exception ex) {
            System.err.println(ex);
        }
    }

    fout.flush();

    br.close();
    fr.close();
}

From source file:com.albert.javatest.JavaTestExample.java

@Ignore
@Test/*from  w  ww  . jav a2 s .  com*/
public void testOenWsSimulatorValidData() {
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;

    try {
        File file = new File("C:\\Projects\\sts-351-osap\\AlbertWeb\\src\\OenWsSimulatorValidData.txt");
        fileReader = new FileReader(file);
        bufferedReader = new BufferedReader(fileReader);

        String line;
        while ((line = bufferedReader.readLine()) != null && !"".equals(line.trim())) {
            Object obj = parser.parse(line);

            JSONObject jsonObject = (JSONObject) obj;

            String dateOfBirth = (String) jsonObject.get("dateOfBirth");
            System.out.println(dateOfBirth);

            String gender = (String) jsonObject.get("gender");
            System.out.println(gender);

            String firstName = (String) jsonObject.get("firstName");
            System.out.println(firstName);

            String surName = (String) jsonObject.get("surName");
            System.out.println(surName);

            String oen = (String) jsonObject.get("oen");
            System.out.println(oen);

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } finally {
        try {
            fileReader.close();
            bufferedReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_correct_metrics_request_parameters() throws Exception {
    // GIVEN//w  w  w.  j av  a  2s.com
    String parserFilePath = "./all-mappings-docs.json";
    Map<String, RequestParamDocumentation> correctNameToTypeMap = new HashMap<String, RequestParamDocumentation>();
    addRequestParamToMap("ids", "string", "** user ids goes here **", true, correctNameToTypeMap);
    addRequestParamToMap("fields", "list", "** The keys from result json can be added as filter**", false,
            correctNameToTypeMap);
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(1);

        JSONArray reqParam = (JSONArray) obj.get("requestParams");

        for (int i = 0; i < reqParam.size(); i++) {
            JSONObject currentParam = (JSONObject) reqParam.get(i);
            String currentName = (String) currentParam.get("name");
            RequestParamDocumentation correctCurrentParam = correctNameToTypeMap.get(currentName);
            Assert.assertEquals((String) currentParam.get("type"), correctCurrentParam.getType());
            Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName());
            Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription());
            Assert.assertEquals(currentParam.get("required"), correctCurrentParam.isRequired());
            // System.out.println(currentParam.get("name"));
            // System.out.println(correctCurrentParam.getName());
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:org.apache.hadoop.mapreduce.util.LinuxResourceCalculatorPlugin.java

/**
 * Read /proc/meminfo, parse and compute memory information
 * @param readAgain if false, read only on the first time
 *//* ww  w .  ja  v  a2  s . com*/
private void readProcMemInfoFile(boolean readAgain) {

    if (readMemInfoFile && !readAgain) {
        return;
    }

    // Read "/proc/memInfo" file
    BufferedReader in = null;
    FileReader fReader = null;
    try {
        fReader = new FileReader(procfsMemFile);
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        return;
    }

    Matcher mat = null;

    try {
        String str = in.readLine();
        while (str != null) {
            mat = PROCFS_MEMFILE_FORMAT.matcher(str);
            if (mat.find()) {
                if (mat.group(1).equals(MEMTOTAL_STRING)) {
                    ramSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(SWAPTOTAL_STRING)) {
                    swapSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(MEMFREE_STRING)) {
                    ramSizeFree = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(SWAPFREE_STRING)) {
                    swapSizeFree = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(INACTIVE_STRING)) {
                    inactiveSize = Long.parseLong(mat.group(2));
                }
            }
            str = in.readLine();
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
    } 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);
        }
    }

    readMemInfoFile = true;
}