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.amaze.filemanager.activities.TextReader.java

public String readTextFile(String fileName) {
    String returnValue = "";
    FileReader file = null;
    String line = "";
    try {//from   w ww. j a v  a2  s  .  co  m
        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);

        while ((line = reader.readLine()) != null) {
            returnValue += line + "\n";

        }
        reader.close();
    } catch (FileNotFoundException e) {
        Toast.makeText(this, utils.getString(this, R.string.cant_read_file), Toast.LENGTH_LONG).show();
        finish();
    } catch (IOException e) {
        Toast.makeText(this, utils.getString(this, R.string.cant_read_file), Toast.LENGTH_LONG).show();
        finish();
    } finally {
        if (file != null) {
            try {
                file.close();

            } catch (IOException e) {
                Toast.makeText(this, utils.getString(this, R.string.cant_read_file), Toast.LENGTH_LONG).show();
                finish();
                e.printStackTrace();
            }
        }
    }

    return returnValue;
}

From source file:com.ibm.dbwkl.request.internal.SetupHandler.java

/**
 * @param configFile//from   www. j av a  2 s .c  o  m
 * @return returns the result after removing the setup lines
 */
private STAFResult RemoveAutoSetup(File configFile) {

    StringBuilder fileContent = new StringBuilder();

    try {
        // make a backup copy
        File backupConfigFile = new File(configFile.getAbsolutePath() + ".backup");
        FileUtils.copyFile(configFile, backupConfigFile);

        // read the file
        FileReader reader = new FileReader(configFile);
        BufferedReader br = new BufferedReader(reader);

        String line = null;
        boolean inDB2WKLSection = false;
        while ((line = br.readLine()) != null) {
            // on the way, remove all db2wkl lines
            if (line.trim().startsWith("# [DB2WKL SETUP]") && inDB2WKLSection == false)
                inDB2WKLSection = true;

            if (!inDB2WKLSection) {
                fileContent.append(line + "\n");

                if (line.trim().startsWith("# [DB2WKL SETUP]") && inDB2WKLSection == true)
                    inDB2WKLSection = false;
            }

        }
        br.close();
        reader.close();

        // write back the whole file
        FileWriter writer = new FileWriter(configFile);
        BufferedWriter bw = new BufferedWriter(writer);

        bw.write(fileContent.toString());

        bw.close();
        writer.close();

        return new STAFResult(STAFResult.Ok);

    } catch (IOException e) {
        Logger.log(
                "Could not remove existing entries in the config file. If the config file is empty/wrong now replace it with the backup STAF.cfg.backup: "
                        + e.getMessage(),
                LogLevel.Error);
        return new STAFResult(STAFResult.FileWriteError);
    }

}

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

@Test
public void check_whether_json_file_will_generate_unsupported_tags() throws IOException, ParseException {
    // GIVEN//from  ww  w.  j av  a 2  s  .c o m
    String parserFilePath = "./all-mappings-docs.json";
    // 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(0);
        JSONObject obj1 = (JSONObject) arr.get(1);
        Assert.assertEquals(obj.get("test"), null);
        Assert.assertEquals(obj1.get("test1"), null);
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:com.talkingdata.orm.tool.ORMGenerateAction.java

private void writeFile(String vm, Map<String, Object> map, FileWriter fileWriter) throws Exception {
    FileReader fileReader = null;
    try {//from   w w  w .ja va  2s  .c  o m
        RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
        InputStream is = ORMGenerateAction.class.getClassLoader().getResourceAsStream(vm);

        File file = File.createTempFile("td_orm_file", ".tmp");
        FileUtils.copyToFile(is, file);
        fileReader = new FileReader(file);

        SimpleNode node = runtimeServices.parse(fileReader, vm);
        Template template = new Template();
        template.setRuntimeServices(runtimeServices);
        template.setData(node);
        template.initDocument();
        template.merge(new VelocityContext(map), fileWriter);
        fileWriter.flush();
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }

        if (fileWriter != null) {
            fileWriter.close();
        }
    }
}

From source file:kjscompiler.Settings.java

public Settings(String path) throws ParseException, FileNotFoundException, IOException {
    JSONParser parser = new JSONParser();
    File file = new File(path);
    String parent = file.exists() ? file.getParent() : null;
    File dir = new File(null == parent || parent.isEmpty() ? "." : parent);
    FileReader fr = new FileReader(file);
    char[] fileData = new char[(int) file.length()];
    fr.read(fileData);//from ww  w . j  a va2s. c om
    String content = new String(fileData);
    JSONObject obj = (JSONObject) parser.parse(content);
    if (obj.get("basedir") instanceof JSONArray) {
        this.baseDir = (JSONArray) obj.get("basedir");
    } else {
        JSONArray arr = new JSONArray();
        arr.add(obj.get("basedir"));
        this.baseDir = arr;
    }
    this.output = (String) obj.get("output");
    this.level = (String) obj.get("level");
    this.pattern = (String) obj.get("pattern");
    this.wrapper = obj.get("wrapper") != null ? (String) obj.get("wrapper") : "";
    this.projectPath = dir.getCanonicalPath();

    dir = new File(this.projectPath, this.output);
    this.output = dir.getCanonicalPath();

    fr.close();
}

From source file:GUI.ReadFile.java

public List<Phase> readPhase(String fileName) {
    FileReader fileReader;
    CSVParser csvFileParser;//from   w w w. jav  a  2  s  . c o  m
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(PHASE_HEADER_MAPPING);
    List<Phase> phase_list = new ArrayList<>();
    try {
        fileReader = new FileReader(fileName);
        //initialize CSVParser object
        csvFileParser = new CSVParser(fileReader, csvFileFormat);
        //Get a list of CSV file records
        List<CSVRecord> csvRecords = csvFileParser.getRecords();
        //Read the CSV file records starting from the second record to skip the header
        for (int i = 1; i < csvRecords.size(); i++) {
            CSVRecord record = csvRecords.get(i);
            Phase p = new Phase(record.get(st_time), record.get(end_time), record.get(category));
            phase_list.add(p);
        }
        fileReader.close();
        csvFileParser.close();
        System.out.println(fileName + " Phase file read!");
    } catch (FileNotFoundException e) {
        System.out.println(fileName + " Phase file missing ...");
        return null;
    } catch (IOException ex) {
        System.out.println(fileName + " csv file error !!!");
        return null;
    } catch (ParseException ex) {
        System.out.println(fileName + " phase parsing error !!!");
        return null;
    }
    return phase_list;
}

From source file:net.flamefeed.ftb.modpackupdater.FileOperator.java

/**
 * This method will download the hash-file from the server and
 * will extract data from it and populate the remoteHashes 2d array.
 *
 * @throws java.lang.IOException/*www . j av  a  2  s.c  o  m*/
 */

private void parseHashfile() throws IOException {
    int numRemoteFiles;
    String[] currentLine;
    FileReader fr;
    BufferedReader br;
    LineNumberReader lnr;

    downloadFile(HASHFILE_NAME);

    /*
     * Compute the number of lines in the hash-file. This corresponds to the
     * number of files on the remote server, and therefore the length of the 
     * hashFiles outer array.
     */

    fr = new FileReader(pathMinecraft + "/" + HASHFILE_NAME);
    lnr = new LineNumberReader(fr);
    lnr.skip(Long.MAX_VALUE);
    numRemoteFiles = lnr.getLineNumber();
    fr.close();

    /*
     * Populate the remoteHashes[][] array with data from the hash file
     */

    remoteHashes = new String[numRemoteFiles][2];

    fr = new FileReader(pathMinecraft + "/" + HASHFILE_NAME);
    br = new BufferedReader(fr);

    /*
     * The hash-file format is as follows:
     * <MD5 hash><tab character><relative filename><newline character>
     * Splitting each line using a tab character "\t" separates the filename
     * from the MD5 hash.
     */

    for (int i = 0; i < numRemoteFiles; i++) {
        currentLine = br.readLine().split("\t", 2);
        remoteHashes[i][MD5HASH] = currentLine[MD5HASH];
        remoteHashes[i][FILENAME] = currentLine[FILENAME];
    }

    fr.close();
}

From source file:org.alfresco.solr.servlet.Solr4X509ServletFilter.java

private void collectSecureComms(File base, Set<String> secureCommsSet) throws IOException {
    File[] files = base.listFiles();

    for (File file : files) {
        if (file.isDirectory()) {
            collectSecureComms(file, secureCommsSet);
        } else {/*w  ww.  jav  a  2s.c  o  m*/

            if (logger.isDebugEnabled()) {
                logger.debug("scanning file:" + file.getAbsolutePath());
            }

            if ("solrcore.properties".equals(file.getName())) {
                FileReader propReader = null;
                Properties props = new Properties();
                try {
                    propReader = new FileReader(file);
                    props.load(propReader);
                    String prop = props.getProperty(SECURE_COMMS);

                    if (prop != null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Found alfresco.secureComms in:" + file.getAbsolutePath() + " : " + prop);
                        }
                        secureCommsSet.add(prop);
                    } else {
                        secureCommsSet.add("none");
                    }
                } finally {
                    propReader.close();
                }
            }
        }
    }
}

From source file:com.sec.ose.osi.util.Property.java

private boolean load() {

    if (mProperty == null) {
        mProperty = new Properties();
        FileReader fr = null;
        try {/* w  ww  . j  a v  a 2s .  c  o  m*/

            File f = new File(PROPERTY_FILE);
            if (f.exists() == false) {
                return false;
            }

            fr = new FileReader(PROPERTY_FILE);
            mProperty.load(fr);

        } catch (FileNotFoundException e) {

            log.warn(e);
            return false;

        } catch (IOException e) {

            log.warn(e);
            return false;

        } catch (Exception e) {
            log.warn(e);
            return false;
        } finally {

            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException e) {

                log.warn(e);
            }
            fr = null;
        }
    }

    return true;
}

From source file:CSVWriter.java

public void testNestedQuotes() {
        String[] data = new String[] { "\"\"", "test" };
        String oracle = new String("\"\"\"\"\"\",\"test\"\n");

        CSVWriter writer = null;//  w w  w .j  ava 2 s  .c o  m
        File tempFile = null;
        FileWriter fwriter = null;

        try {
            tempFile = File.createTempFile("csvWriterTest", ".csv");
            tempFile.deleteOnExit();
            fwriter = new FileWriter(tempFile);
            writer = new CSVWriter(fwriter);
        } catch (IOException e) {
            fail();
        }

        // write the test data:
        writer.writeNext(data);

        try {
            writer.close();
        } catch (IOException e) {
            fail();
        }

        try {
            // assert that the writer was also closed.
            fwriter.flush();
            fail();
        } catch (IOException e) {
            // we should go through here..
        }

        // read the data and compare.
        FileReader in = null;
        try {
            in = new FileReader(tempFile);
        } catch (FileNotFoundException e) {
            fail();
        }

        StringBuffer fileContents = new StringBuffer();
        try {
            int ch;
            while ((ch = in.read()) != -1) {
                fileContents.append((char) ch);
            }
            in.close();
        } catch (IOException e) {
            fail();
        }

        assertTrue(oracle.equals(fileContents.toString()));
    }