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.photon.phresco.framework.rest.api.RepositoryService.java

/**
 * Update latest project.//from w w  w  .j  a v  a  2 s .  c  o  m
 *
 * @param user the user
 * @param projectId the project id
 * @param appId the app id
 * @throws PhrescoException the phresco exception
 */
private void updateLatestProject(User user, String projectId, String appId) throws PhrescoException {
    try {
        File tempPath = new File(Utility.getPhrescoTemp() + File.separator + USER_PROJECT_JSON);
        JSONObject userProjJson = null;
        JSONParser parser = new JSONParser();
        if (tempPath.exists()) {
            FileReader reader = new FileReader(tempPath);
            userProjJson = (JSONObject) parser.parse(reader);
            reader.close();
        } else {
            userProjJson = new JSONObject();
        }

        userProjJson.put(user.getId(), projectId + Constants.STR_COMMA + appId);
        FileWriter writer = new FileWriter(tempPath);
        writer.write(userProjJson.toString());
        writer.close();
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (ParseException e) {
        throw new PhrescoException(e);
    }
}

From source file:org.gwaspi.reports.PlinkReportLoaderCombined.java

public static CombinedRangeXYPlot loadAssocUnadjLogPvsPos(File plinkReport, Set<String> redMarkers)
        throws IOException {

    NumberAxis sharedAxis = new NumberAxis("-log?(P)");
    sharedAxis.setTickMarkInsideLength(3.0f);
    CombinedRangeXYPlot combinedPlot = new CombinedRangeXYPlot(sharedAxis);
    combinedPlot.setGap(0);//  ww  w.j  a  v  a2 s .c om

    XYSeries series1 = null;
    XYSeries series2 = null;
    FileReader inputFileReader = null;
    BufferedReader inputBufferReader = null;
    try {
        inputFileReader = new FileReader(plinkReport);
        inputBufferReader = new BufferedReader(inputFileReader);

        // Getting data from file and subdividing to series all points by chromosome
        String l;
        String tempChr = "";
        // read but ignore the header
        /*String header = */inputBufferReader.readLine();
        int count = 0;
        while ((l = inputBufferReader.readLine()) != null) {
            if (count % 10000 == 0) {
                log.info("loadAssocUnadjLogPvsPos -> reader count: {}", count);
            }
            count++;

            l = l.trim().replaceAll("\\s+", ",");
            String[] cVals = l.split(",");
            String markerId = cVals[1];
            int position = Integer.parseInt(cVals[2]);
            String s_pVal = cVals[8];

            if (!s_pVal.equals("NA")) {
                double pValue = Double.parseDouble(s_pVal); // P value

                if (cVals[0].toString().equals(tempChr)) {
                    if (redMarkers.contains(markerId)) { // Insert in alternate color series
                        series2.add(position, pValue);
                    } else {
                        series1.add(position, pValue);
                    }

                    //                  series1.add(position, logPValue);
                } else {
                    if (!tempChr.isEmpty()) { // Not the first time round!
                        XYSeriesCollection tempChrData = new XYSeriesCollection();
                        tempChrData.addSeries(series1);
                        tempChrData.addSeries(series2);
                        appendToCombinedRangePlot(combinedPlot, tempChr, tempChrData, false);
                    }

                    tempChr = cVals[0];
                    series1 = new XYSeries("Imputed");
                    series2 = new XYSeries("Observed"); // Alternate color series
                    if (redMarkers.contains(markerId)) { // Insert inlternate color series
                        series2.add(position, pValue);
                    } else {
                        series1.add(position, pValue);
                    }

                    //                  series1 = new XYSeries(cVals[0]);
                    //                  series1.add(position, logPValue);
                }
            }
        }
        // Append last chromosome to combined plot
        XYSeriesCollection tempChrData = new XYSeriesCollection();
        tempChrData.addSeries(series1);
        tempChrData.addSeries(series2);
        appendToCombinedRangePlot(combinedPlot, tempChr, tempChrData, true);
    } finally {
        try {
            if (inputBufferReader != null) {
                inputBufferReader.close();
            } else if (inputFileReader != null) {
                inputFileReader.close();
            }
        } catch (Exception ex) {
            log.warn(null, ex);
        }
    }

    return combinedPlot;
}

From source file:com.sec.ose.osi.ui.frm.main.identification.codematch.JPanCodeMatchMain.java

private void setMySourceCode(String fileName) {
    sbMySourceNum.delete(0, sbMySourceNum.length());
    sbMySourceText.delete(0, sbMySourceText.length());

    log.debug("setMySourceCode: " + fileName);

    String projectName = IdentifyMediator.getInstance().getSelectedProjectName();
    File mySourceCode = new File(protexSDK.getSourceLocation(projectName) + File.separator + fileName);

    log.debug("mySourceCode: " + mySourceCode.getAbsolutePath());

    getJPanMatchedSourceViewLeft().clear();
    if (mySourceCode.exists()) {
        FileReader fr = null;
        try {/*  ww  w  .j ava2  s  . c  o m*/
            fr = new FileReader(mySourceCode);
            BufferedReader br = new BufferedReader(fr);
            String tmpStr = null;
            int curLine = 1;
            while ((tmpStr = br.readLine()) != null) {
                sbMySourceNum.append(String.valueOf(curLine) + "\n");
                sbMySourceText.append(tmpStr + "\n");
                curLine++;
            }

            getJPanMatchedSourceViewLeft().setText(sbMySourceText.toString(), sbMySourceNum.toString());
        } catch (Exception e) {
            log.warn(e.getMessage());
            getJPanMatchedSourceViewLeft().clear();
            getJPanMatchedSourceViewLeft()
                    .setText(mySourceCode.getAbsolutePath() + "\n" + NO_SOURCE_CODE_NOT_EXIST_IN_LOCAL);
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (Exception e) {
                log.warn(e);
            }
        }
    } else {
        getJPanMatchedSourceViewLeft()
                .setText(mySourceCode.getAbsolutePath() + "\n" + NO_SOURCE_CODE_NOT_EXIST_IN_LOCAL);
    }

    getJPanMatchedSourceViewLeft().clearStyle();

}

From source file:org.dspace.app.statistics.LogAnalyser.java

/**
 * Read in the given config file and populate the class globals.
 *
 * @param   configFile  the config file to read in
 * @throws IOException if IO error/*from w w w .ja  v a  2s  .co m*/
 */
public static void readConfig(String configFile) throws IOException {
    //instantiate aggregators
    actionAggregator = new HashMap<String, Integer>();
    searchAggregator = new HashMap<String, Integer>();
    userAggregator = new HashMap<String, Integer>();
    itemAggregator = new HashMap<String, Integer>();
    archiveStats = new HashMap<String, Integer>();

    //instantiate lists
    generalSummary = new ArrayList<String>();
    excludeWords = new ArrayList<String>();
    excludeTypes = new ArrayList<String>();
    excludeChars = new ArrayList<String>();
    itemTypes = new ArrayList<String>();

    // prepare our standard file readers and buffered readers
    FileReader fr = null;
    BufferedReader br = null;

    String record = null;
    try {
        fr = new FileReader(configFile);
        br = new BufferedReader(fr);
    } catch (IOException e) {
        System.out.println("Failed to read config file: " + configFile);
        System.exit(0);
    }

    // read in the config file and set up our instance variables
    while ((record = br.readLine()) != null) {
        // check to see what kind of line we have
        Matcher matchComment = comment.matcher(record);
        Matcher matchReal = real.matcher(record);

        // if the line is not a comment and is real, read it in
        if (!matchComment.matches() && matchReal.matches()) {
            // lift the values out of the matcher's result groups
            String key = matchReal.group(1).trim();
            String value = matchReal.group(2).trim();

            // read the config values into our instance variables (see 
            // documentation for more info on config params)
            if (key.equals("general.summary")) {
                actionAggregator.put(value, Integer.valueOf(0));
                generalSummary.add(value);
            }

            if (key.equals("exclude.word")) {
                excludeWords.add(value);
            }

            if (key.equals("exclude.type")) {
                excludeTypes.add(value);
            }

            if (key.equals("exclude.character")) {
                excludeChars.add(value);
            }

            if (key.equals("item.type")) {
                itemTypes.add(value);
            }

            if (key.equals("item.floor")) {
                itemFloor = Integer.parseInt(value);
            }

            if (key.equals("search.floor")) {
                searchFloor = Integer.parseInt(value);
            }

            if (key.equals("item.lookup")) {
                itemLookup = Integer.parseInt(value);
            }

            if (key.equals("user.email")) {
                userEmail = value;
            }
        }
    }

    // close the inputs
    br.close();
    fr.close();

    return;
}

From source file:big.BigZip.java

/**
 * Looks inside a textWeird file to discover the line that contains a given
keyword. When the line is discovered then it returns an array where
 * the first long represents the start of data and the second represents
 * its end./*ww w.  j  ava  2 s  .com*/
 * @param file      A file on disk
 * @param keyword   A keyword that must be present on the file
 * @return          An array with the start and end position of a given
 * file inside our BIG archive. If we don't have a match, the result is NULL
 */
private long[] getFileCoordinates(final File file, final String keyword) {
    // what we provide as answer
    long[] result = null;
    BufferedReader reader;
    try {
        FileReader fileReader = new FileReader(file);
        reader = new BufferedReader(fileReader);
        String line = "";
        while (line != null) {
            // do we have a match? Yes, let's proceed
            if (line.endsWith(keyword)) {
                // an example of what we are reading:
                // 000000000180411 3f1f0990b8200b5e9b5de461a7fa7f7640ae16f7 /C/HappyNuno.txt
                final String startValue = line.substring(0, 15);
                // get the coordinate and ignore the magic signature size to get the raw binary contents
                final long val1 = Long.parseLong(startValue) + magicSignature.length();
                // now read the next line to get the end value
                line = reader.readLine();
                final String endValue = line.substring(0, 15);
                final long val2 = Long.parseLong(endValue);
                // deliver the value
                result = new long[] { val1, val2 };
                break;
            }
            line = reader.readLine();
        }
        fileReader.close();
        reader.close();
    } catch (IOException ex) {
        Logger.getLogger(files.class.getName()).log(Level.SEVERE, null, ex);
    }
    // all done    
    return result;
}

From source file:base.BasePlayer.AddGenome.java

static void makeGenomes() {
    try {//from   w  w  w.ja  v  a 2s  . c  o m
        FileReader freader = null;
        File file = new File(Main.genomeDir.getCanonicalPath() + "/ensembl.txt");
        if (file.exists()) {
            freader = new FileReader(file);

            BufferedReader reader = new BufferedReader(freader);
            String line, name;
            String[] split;

            while ((line = reader.readLine()) != null) {
                split = line.split("\t");
                name = split[0].substring(split[0].lastIndexOf("/") + 1, split[0].indexOf(".dna."));
                organisms.add(name);
                if (split[0].contains("GRCh38")) {
                    split[0] = split[0].replace("toplevel", "primary_assembly");
                }
                if (split.length == 5) {
                    URL[] urls = { new URL(split[0]), new URL(split[2]), new URL(split[4]) };
                    genomeHash.put(name, urls);
                } else {
                    URL[] urls = { new URL(split[0]), new URL(split[2]) };
                    genomeHash.put(name, urls);
                }
                Integer[] sizes = { Integer.parseInt(split[1]), Integer.parseInt(split[3]) };
                sizeHash.put(name, sizes);
            }

            freader.close();
            reader.close();
        }
        file = new File(Main.genomeDir.getCanonicalPath() + "/ensembl_fetched.txt");
        if (file.exists()) {

            freader = new FileReader(file);

            BufferedReader reader = new BufferedReader(freader);
            String line, name;
            String[] split;
            while ((line = reader.readLine()) != null) {
                split = line.split("\t");
                name = split[0].substring(split[0].lastIndexOf("/") + 1, split[0].indexOf(".dna."));
                organisms.add(name);
                if (split[0].contains("GRCh38")) {
                    split[0] = split[0].replace("toplevel", "primary_assembly");
                }
                if (split.length == 5) {
                    URL[] urls = { new URL(split[0]), new URL(split[2]), new URL(split[4]) };
                    genomeHash.put(name, urls);
                } else {
                    URL[] urls = { new URL(split[0]), new URL(split[2]) };
                    genomeHash.put(name, urls);
                }
                Integer[] sizes = { Integer.parseInt(split[1]), Integer.parseInt(split[3]) };
                sizeHash.put(name, sizes);
            }
            freader.close();
            reader.close();
        }
        /*      URL[] urls = {new URL("ftp://ftp.ensembl.org/pub/grch37/release-83/fasta/homo_sapiens/dna/Homo_sapiens.GRCh37.dna.primary_assembly.fa.gz"),
            new URL("ftp://ftp.ensembl.org/pub/grch37/update/gff3/homo_sapiens/Homo_sapiens.GRCh37.82.gff3.gz"),
            new URL("http://hgdownload.cse.ucsc.edu/goldenPath/hg19/database/cytoBand.txt.gz")};
              Integer[] sizes = new Integer[2];
              sizes[0] = 900;
              sizes[1] = 40;
              sizeHash.put("Homo_sapiens_GRCh37", sizes);
              genomeHash.put("Homo_sapiens_GRCh37", urls);
                      
           /*   URL[] urls2 = {new URL("ftp://ftp.ensembl.org/pub/grch37/release-83/fasta/homo_sapiens/dna/Homo_sapiens.GRCh37.dna.primary_assembly.fa.gz"),
         new URL("ftp://ftp.ncbi.nlm.nih.gov/genomes/H_sapiens/ARCHIVE/BUILD.37.3/GFF/ref_GRCh37.p5_top_level.gff3.gz"),
         new URL("http://hgdownload.cse.ucsc.edu/goldenPath/hg19/database/cytoBand.txt.gz") };
              sizes = new Integer[2];
              sizes[0] = 900;
              sizes[1] = 35;
              sizeHash.put("Homo_sapiens_GRCh37:RefSeq_genes", sizes);
              genomeHash.put("Homo_sapiens_GRCh37:RefSeq_genes", urls2);
              */
        /*   URL[] urls3 = { new URL("ftp://ftp.ensembl.org/pub/release-85/fasta/ciona_intestinalis/dna/Ciona_intestinalis.KH.dna.toplevel.fa.gz"),
          new URL("ftp://ftp.ensembl.org/pub/release-85/gff3/ciona_intestinalis/Ciona_intestinalis.KH.85.gff3.gz")
           };
           sizes = new Integer[2];
           sizes[0] = 34;
           sizes[1] = 5;
           sizeHash.put("Ciona_intestinalis", sizes);
           genomeHash.put("Ciona_intestinalis", urls3);
                   
           URL[] urls4 = { new URL("ftp://ftp.ensembl.org/pub/release-85/fasta/saccharomyces_cerevisiae/dna/Saccharomyces_cerevisiae.R64-1-1.dna.toplevel.fa.gz"),
                 new URL("ftp://ftp.ensembl.org/pub/release-85/gff3/saccharomyces_cerevisiae/Saccharomyces_cerevisiae.R64-1-1.85.gff3.gz")
           };
           sizes = new Integer[2];
           sizes[0] = 4;
           sizes[1] = 1;
           sizeHash.put("Saccharomyces_cerevisiae", sizes);
           genomeHash.put("Saccharomyces_cerevisiae", urls4);
                   
           URL[] urls5 = {new URL("ftp://ftp.ensembl.org/pub/release-85/fasta/mus_musculus/dna/Mus_musculus.GRCm38.dna.toplevel.fa.gz"),
         new URL("ftp://ftp.ensembl.org/pub/release-85/gff3/mus_musculus/Mus_musculus.GRCm38.85.gff3.gz"),
         new URL("http://hgdownload.cse.ucsc.edu/goldenPath/mm10/database/cytoBand.txt.gz")};
                   
           sizes = new Integer[2];
           sizes[0] = 801;
           sizes[1] = 58;
           sizeHash.put("Mus_musculus_GRCm38", sizes);
           genomeHash.put("Mus_musculus_GRCm38", urls5);
                   
        /*   URL[] urls6 = {new URL("ftp://ftp.ensembl.org/pub/release-85/fasta/mus_musculus/dna/Mus_musculus.GRCm38.dna.toplevel.fa.gz"),
         new URL("ftp://ftp.ncbi.nlm.nih.gov/genomes/M_musculus/GFF/ref_GRCm38.p4_top_level.gff3.gz") };
           sizes = new Integer[2];
           sizes[0] = 801;
           sizes[1] = 28;
           sizeHash.put("Mus_musculus_GRCm38:RefSeq_genes", sizes);
           genomeHash.put("Mus_musculus_GRCm38:RefSeq_genes", urls6);
                   
           URL[] urls7 = {new URL("ftp://ftp.ensembl.org/pub/release-85/fasta/rattus_norvegicus/dna/Rattus_norvegicus.Rnor_6.0.dna.toplevel.fa.gz"),
         new URL("ftp://ftp.ensembl.org/pub/release-85/gff3/rattus_norvegicus/Rattus_norvegicus.Rnor_6.0.85.gff3.gz") };
           sizes = new Integer[2];
           sizes[0] = 812;
           sizes[1] = 15;
           sizeHash.put("Rattus_norvegicus", sizes);
           genomeHash.put("Rattus_norvegicus", urls7);
                   
                   
           URL[] urls8 = {new URL("ftp://ftp.ensembl.org/pub/release-85/fasta/homo_sapiens/dna/Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz"),
         new URL("ftp://ftp.ensembl.org/pub/release-85/gff3/homo_sapiens/Homo_sapiens.GRCh38.85.gff3.gz"),
         new URL("http://hgdownload.cse.ucsc.edu/goldenPath/hg38/database/cytoBand.txt.gz")};
           sizes = new Integer[2];
           sizes[0] = 860;
           sizes[1] = 38;
           sizeHash.put("Homo_sapiens_GRCh38", sizes);
           genomeHash.put("Homo_sapiens_GRCh38", urls8);
                
           /*URL[] urls9 = {new URL("ftp://ftp.ensembl.org/pub/release-85/fasta/homo_sapiens/dna/Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz"),
         new URL("ftp://ftp.ncbi.nlm.nih.gov/genomes/H_sapiens/GFF/ref_GRCh38.p7_top_level.gff3.gz"),
         new URL("http://hgdownload.cse.ucsc.edu/goldenPath/hg38/database/cytoBand.txt.gz")};
           sizes = new Integer[2];
           sizes[0] = 860;
           sizes[1] = 41;
           sizeHash.put("Homo_sapiens_GRCh38:RefSeq_genes", sizes);
           genomeHash.put("Homo_sapiens_GRCh38:RefSeq_genes", urls9);
        */
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.xoriant.akka.mongodb.bulkimport.actor.FileReaderActor.java

private void readAndInsertCSV(String filePath) {
    FileReader fileReader = null;

    CSVParser csvFileParser = null;/*from  w  ww  .  j av a  2  s  . co  m*/

    // Create the CSVFormat object with the header mapping
    CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader(FILE_HEADER_MAPPING);

    try {

        fileReader = new FileReader(filePath);

        csvFileParser = new CSVParser(fileReader, csvFileFormat);

        List<CSVRecord> csvRecords = csvFileParser.getRecords();
        CSVRecordBatchMsg csvRecordBatch = new CSVRecordBatchMsg();
        boolean batchSent = false;
        // Skip the header row and start reading CSV records
        for (int i = 1; i < csvRecords.size(); i++) {
            CSVRecord record = csvRecords.get(i);
            BasicDBObject person = new BasicDBObject();
            person.put(PERSON_GENDER, record.get(PERSON_GENDER));
            person.put(PERSON_TITLE, record.get(PERSON_TITLE));
            person.put(PERSON_NAMESET, record.get(PERSON_NAMESET));
            person.put(PERSON_SURNAME, record.get(PERSON_SURNAME));
            person.put(PERSON_CITY, record.get(PERSON_CITY));
            person.put(PERSON_STATE, record.get(PERSON_STATE));
            person.put(PERSON_ZIPCODE, record.get(PERSON_ZIPCODE));
            csvRecordBatch.add(person);
            batchSent = false;
            if (i % batchSize == 0) {
                batchSentCounter++;
                csvRecordBatch.setBatchNo(batchSentCounter);
                mongoInsertionActor.tell(csvRecordBatch, getSelf());
                csvRecordBatch = new CSVRecordBatchMsg();
                batchSent = true;
            }

        }

        // Last batch maybe pending if there are less than batch size left over records. Sending last batch of such records explicitly
        if (!batchSent) {
            batchSentCounter++;
            csvRecordBatch.setBatchNo(batchSentCounter);
            mongoInsertionActor.tell(csvRecordBatch, getSelf());
        }
        mongoInsertionActor.tell(new EndOfFileMsg(), getSelf());
        System.out.println("FileReaderActor: EOF sent");

    } catch (Exception e) {
        System.out.println("Error in CsvFileReader !!!" + e.getMessage());
    } finally {
        try {
            fileReader.close();
            csvFileParser.close();
        } catch (IOException e) {
            System.out.println("Error while closing fileReader/csvFileParser : " + e.getMessage());
        }
    }

}

From source file:org.apache.jetspeed.modules.actions.portlets.PsmlManagerAction.java

/**
 * Load a PSMLDOcument from disk// ww w .  j a va 2  s. co m
 *
 * @param fileOrUrl a String representing either an absolute URL or an
 * absolute filepath
 */
private PSMLDocument loadDocument(String fileOrUrl) {
    PSMLDocument doc = null;

    if (fileOrUrl != null) {

        // we'll assume the name is the the location of the file
        File f = null;

        f = new File(fileOrUrl);

        if (!f.exists()) {
            return null;
        }

        doc = new BasePSMLDocument();
        doc.setName(fileOrUrl);

        // now that we have a file reference, try to load the serialized PSML
        Portlets portlets = null;
        FileReader reader = null;
        try {
            reader = new FileReader(f);

            Unmarshaller unmarshaller = new Unmarshaller(this.loadMapping());
            portlets = (Portlets) unmarshaller.unmarshal(reader);

            doc.setPortlets(portlets);

        } catch (IOException e) {
            logger.error("PsmlManagerAction: Could not load the file " + f.getAbsolutePath(), e);
        } catch (MarshalException e) {
            logger.error("PsmlManagerAction: Could not unmarshal the file " + f.getAbsolutePath(), e);
        } catch (MappingException e) {
            logger.error("PsmlManagerAction: Could not unmarshal the file " + f.getAbsolutePath(), e);
        } catch (ValidationException e) {
            logger.error("PsmlManagerAction: document " + f.getAbsolutePath() + " is not valid", e);
        } catch (Exception e) {
            logger.error("PsmlManagerAction: Error while loading  " + f.getAbsolutePath(), e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }

    return doc;
}

From source file:SWTFileViewerDemo.java

/**
 * Copies a file or entire directory structure.
 * //  w w  w .  j ava  2s.  c o m
 * @param oldFile
 *            the location of the old file or directory
 * @param newFile
 *            the location of the new file or directory
 * @return true iff the operation succeeds without errors
 */
boolean copyFileStructure(File oldFile, File newFile) {
    if (oldFile == null || newFile == null)
        return false;

    // ensure that newFile is not a child of oldFile or a dupe
    File searchFile = newFile;
    do {
        if (oldFile.equals(searchFile))
            return false;
        searchFile = searchFile.getParentFile();
    } while (searchFile != null);

    if (oldFile.isDirectory()) {
        /*
         * Copy a directory
         */
        if (progressDialog != null) {
            progressDialog.setDetailFile(oldFile, ProgressDialog.COPY);
        }
        if (simulateOnly) {
            // System.out.println(getResourceString("simulate.DirectoriesCreated.text",
            // new Object[] { newFile.getPath() }));
        } else {
            if (!newFile.mkdirs())
                return false;
        }
        File[] subFiles = oldFile.listFiles();
        if (subFiles != null) {
            if (progressDialog != null) {
                progressDialog.addWorkUnits(subFiles.length);
            }
            for (int i = 0; i < subFiles.length; i++) {
                File oldSubFile = subFiles[i];
                File newSubFile = new File(newFile, oldSubFile.getName());
                if (!copyFileStructure(oldSubFile, newSubFile))
                    return false;
                if (progressDialog != null) {
                    progressDialog.addProgress(1);
                    if (progressDialog.isCancelled())
                        return false;
                }
            }
        }
    } else {
        /*
         * Copy a file
         */
        if (simulateOnly) {
            // System.out.println(getResourceString("simulate.CopyFromTo.text",
            // new Object[] { oldFile.getPath(), newFile.getPath() }));
        } else {
            FileReader in = null;
            FileWriter out = null;
            try {
                in = new FileReader(oldFile);
                out = new FileWriter(newFile);

                int count;
                while ((count = in.read()) != -1)
                    out.write(count);
            } catch (FileNotFoundException e) {
                return false;
            } catch (IOException e) {
                return false;
            } finally {
                try {
                    if (in != null)
                        in.close();
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    return false;
                }
            }
        }
    }
    return true;
}

From source file:org.fhaes.jsea.JSEAFrame.java

/**
 * Parse the events file to extract years with events
 * //  w ww.  ja v  a2s  . c om
 * @return
 */
public Boolean parseEventListFile() {

    File f = new File(this.txtEventListFile.getText());
    if (!f.exists()) {
        log.error("Event list file does not exist");
        return false;
    }

    FileReader fr = null;
    BufferedReader br = null;
    String record = null;
    events = new ArrayList<Integer>();

    try {
        fr = new FileReader(txtEventListFile.getText());
        br = new BufferedReader(fr);

        while ((record = br.readLine()) != null) {
            if (!record.contains("*")) {

                try {
                    events.add(new Integer(record));
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(this,
                            "The event file must contain a list of integer values after any comment lines.\nPlease check the file and try again.",
                            "Warning", JOptionPane.ERROR_MESSAGE);
                    txtEventListFile.setText("");
                    fr.close();
                    br.close();
                    return false;
                }

            }
        }
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "Error reading events file.\nPlease check the file and try again.",
                "Warning", JOptionPane.ERROR_MESSAGE);
        txtEventListFile.setText("");

        return false;
    } finally {
        try {
            fr.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    Collections.sort(events);

    return true;
}