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:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

/**
 * Restituisce l'encoding del file specificato.
 *
 * @param file Il file di cui ricavare l'encoding.
 * @return L'encoding del file specificato.
 *//*  w  w w.jav a  2 s  .  co m*/
private String getEncoding(File file) {
    String encoding = "";
    try {
        FileReader fr = new FileReader(file);
        encoding = fr.getEncoding();
        fr.close();
    } catch (Exception e) {
    }
    return encoding;
}

From source file:ca.uvic.cs.tagsea.statistics.svn.jobs.SVNCommentScanningJob.java

protected IStatus run(IProgressMonitor monitor) {
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    ISVNClientAdapter client;// ww  w.  jav a 2s . com
    List svnResources = new LinkedList();
    for (int i = 0; i < projects.length; i++) {
        IProject project = projects[i];
        ISVNLocalResource r = SVNWorkspaceRoot.getSVNResourceFor(project);
        try {
            if (r != null && r.isManaged()) {
                svnResources.add(r);
            }
        } catch (SVNException e) {
            //do nothing, continue t the next
        }
    }
    monitor.beginTask("Scanning subversion projects...", svnResources.size() * 1000000);
    IPath state = SVNStatistics.getDefault().getStateLocation();
    File tempdir = state.append("temp").toFile();
    if (!tempdir.isDirectory()) {
        if (tempdir.exists()) {
            tempdir.delete();
        }
        tempdir.mkdir();
    }
    deleteTemps(tempdir);

    for (Iterator it = svnResources.iterator(); it.hasNext();) {
        ISVNLocalResource svnProject = (ISVNLocalResource) it.next();
        //used to make sure that we don't repeat old comments.
        HashMap fileCommentsMap = new HashMap();
        fileEntryMap = new HashMap();
        monitor.subTask("Getting project information for " + svnProject.getName());
        //create a temp file for each project. They will be uploaded
        //to the server.
        String projectName = svnProject.getName(); //names are guaranteed unique

        try {
            ISVNRemoteResource remote = null;
            for (int tries = 0; remote == null && tries < 10; tries++) {
                try {
                    remote = svnProject.getLatestRemoteResource();
                } catch (Exception e) {
                }
                ;
                if (remote == null) {
                    SVNStatistics.getDefault().getLog().log(new Status(IStatus.WARNING, SVNStatistics.PLUGIN_ID,
                            IStatus.WARNING,
                            "could not get remote resource for " + svnProject.getName() + "... trying again.",
                            null));
                    try {
                        //                     @tag tagsea.bug.subclipse : it seems that sublcipse has a synchronization problem. Wait a little while and try again.
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        return new Status(IStatus.ERROR, SVNProviderPlugin.ID, IStatus.ERROR,
                                "Could not communicate with remote resource.", null);
                    }
                }
            }
            if (remote == null) {
                SVNStatistics.getDefault().getLog().log(new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0,
                        "Could not get a remote resource", null));
                monitor.worked(1000000);
                continue;
            }
            ISVNRepositoryLocation repository = remote.getRepository();

            client = repository.getSVNClient();
            //            @tag tagsea.statistics.enhance : It seems best to use this password callback because that way, the passwords can be saved with the workspace. But, it might be confusing to see for the first time.
            client.addPasswordCallback(SVNProviderPlugin.getPlugin().getSvnPromptUserPassword());
            SVNRevision.Number revision = remote.getLastChangedRevision();

            long revNum = revision.getNumber();
            int revisionWork = 1000000;
            ILogEntry[] entries;
            try {
                entries = remote.getLogEntries(new NullProgressMonitor());
            } catch (TeamException e1) {
                monitor.worked(revisionWork);
                e1.printStackTrace();
                continue;
            }
            if (revNum > 0) {
                revisionWork = 1000000 / (int) revNum;
            }
            for (int ei = 0; ei < entries.length; ei++) {
                ILogEntry entry = entries[ei];
                revision = entry.getRevision();
                File tempFile = state.append(
                        projectName + "." + getDateString() + "." + revision.getNumber() + ".comments.txt")
                        .toFile();
                if (tempFile.exists()) {
                    tempFile.delete();
                }
                try {
                    tempFile.createNewFile();
                } catch (IOException e) {
                    //skip to the next one.
                    continue;
                }
                PrintStream out;
                try {
                    out = new PrintStream(tempFile);
                } catch (IOException e) {
                    continue;
                }

                out.println(remote.getUrl() + " Revision:" + revision.getNumber());
                monitor.subTask("Finding java resources: " + svnProject.getName() + "...");
                SubProgressMonitor revMonitor = new SubProgressMonitor(monitor, revisionWork);
                if (monitor.isCanceled()) {
                    return Status.CANCEL_STATUS;
                }
                monitor.subTask("temporarily checking out " + svnProject.getName() + "...");
                SubProgressMonitor subPm = new SubProgressMonitor(revMonitor, 10);
                try {
                    OperationManager.getInstance().beginOperation(client,
                            new OperationProgressNotifyListener(subPm));
                    client.checkout(remote.getUrl(), new File(tempdir, svnProject.getName()), revision, true);
                } catch (SVNClientException e) {
                    //I wish that there were a better way to do this, but it seem that we
                    //have to just keep decrementing it.
                    revMonitor.done();
                    revNum--;
                    revision = new SVNRevision.Number(revNum);
                    continue;
                } finally {
                    OperationManager.getInstance().endOperation();
                    subPm.done();
                }
                if (monitor.isCanceled()) {
                    return Status.CANCEL_STATUS;
                }
                List files = findJavaFiles(tempdir);
                int work = 0;
                if (files.size() > 0) {
                    work = (revisionWork - 20) / files.size();
                    for (Iterator fit = files.iterator(); fit.hasNext();) {
                        File file = (File) fit.next();

                        monitor.subTask("Scanning java file....");
                        TreeSet commentSet = (TreeSet) fileCommentsMap.get(file.getAbsolutePath());
                        if (commentSet == null) {
                            commentSet = new TreeSet();
                            fileCommentsMap.put(file.getAbsolutePath(), commentSet);
                        }
                        FileReader reader = new FileReader(file);
                        StringBuilder builder = new StringBuilder();
                        char[] buffer = new char[1024];
                        int read = 0;
                        while ((read = reader.read(buffer)) >= 0) {
                            builder.append(buffer, 0, read);
                        }
                        reader.close();
                        ISVNAnnotations ann = null;
                        try {
                            //get blame information.
                            List fileLogs = getLogEntries(file, client, repository);
                            //don't do extra work if this file doesn't have a log for this revision.
                            if (!checkRevision(fileLogs, revision)) {
                                monitor.worked(work);
                                //System.out.println("Skipped " + file.getAbsolutePath() + " revision " + revision.getNumber());
                                continue;
                            }
                            ann = client.annotate(file, revision, revision);
                        } catch (SVNClientException e) {
                        } catch (TeamException e) {
                        }
                        if (monitor.isCanceled()) {
                            return Status.CANCEL_STATUS;
                        }
                        SubProgressMonitor scanMonitor = new SubProgressMonitor(revMonitor, work);
                        Stats s = SimpleJavaCodeScanner.scan(builder.toString(), scanMonitor);
                        if (monitor.isCanceled()) {
                            return Status.CANCEL_STATUS;
                        }
                        monitor.worked(work);
                        out.println("New/Changed Tags:");
                        for (int ci = 0; ci < s.TAGS.length; ci++) {
                            Comment c = s.TAGS[ci];
                            if (!commentSet.contains(c)) {
                                commentSet.add(c);
                                String author = getAuthor(c, ann);
                                out.println(c.toString() + "\tauthor=" + author);
                            }
                        }
                        out.println("New/Changed Tasks:");
                        for (int ci = 0; ci < s.TASKS.length; ci++) {
                            Comment c = s.TASKS[ci];
                            if (!commentSet.contains(c)) {
                                commentSet.add(c);
                                String author = getAuthor(c, ann);
                                out.println(c.toString() + "\tauthor=" + author);
                            }
                        }
                        out.println("New/Changed Other:");
                        for (int ci = 0; ci < s.NONTAGS.length; ci++) {
                            Comment c = s.NONTAGS[ci];
                            if (!commentSet.contains(c)) {
                                commentSet.add(c);
                                String author = getAuthor(c, ann);
                                out.println(c.toString() + "\tauthor=" + author);
                            }
                        }

                        if (monitor.isCanceled()) {
                            return Status.CANCEL_STATUS;
                        }
                    }
                }
                if (work == 0) {
                    revMonitor.worked(revisionWork - 10);
                }
                monitor.subTask("Sending and Deleting temporary files...");
                out.close();
                sendFile(tempFile);
                deleteTemps(tempdir);
                if (monitor.isCanceled()) {
                    return Status.CANCEL_STATUS;
                }
                revMonitor.done();
                monitor.worked(revisionWork - 20);

            }
        } catch (SVNException e) {
            return new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, e.getMessage(), e);
        } catch (IOException e) {
            return new Status(IStatus.ERROR, SVNStatistics.PLUGIN_ID, 0, e.getMessage(), e);
        }
    }
    return Status.OK_STATUS;
}

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

/**
 * <p>/*from ww  w  .  ja  va 2  s .c om*/
 * acceptDeep</p>
 *
 * @param parm a {@link java.io.File} object.
 * @return a boolean.
 */
public boolean acceptDeep(File parm) {
    try {
        if (parm == null || parm.isDirectory() || !parm.canRead()) {
            return false;
        }
        FileReader fr = new FileReader(parm);
        BufferedReader br = new BufferedReader(fr);
        if (!br.ready()) {
            // Empty File?
            return false;
        }
        // If the first token is not an integer this file is not
        // an Internal Coordinates 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
        // three tokens, it is not an internal 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 != 3) {
            return false;
        }
        try {
            Integer.parseInt(data[0]);
        } catch (Exception e) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return true;
    }
}

From source file:org.intermine.bio.dataconversion.FastaLoaderTask.java

/**
 * Handles each fasta file. Factored out so we can supply files for testing.
 *
 * @param file the File to process.//ww w.j  ava 2s.  c o m
 * @throws BuildException if the is a problem
 */
@Override
public void processFile(File file) {
    try {
        FileReader fileReader = new FileReader(file);
        BufferedReader reader = new BufferedReader(fileReader);

        System.err.println("reading " + sequenceType + " sequence from: " + file);

        SequenceIterator iter = (SequenceIterator) SeqIOTools.fileToBiojava("fasta", sequenceType, reader);

        if (!iter.hasNext()) {
            System.err.println("no fasta sequences found - exiting");
            return;
        }

        while (iter.hasNext()) {
            Sequence bioJavaSequence = iter.nextSequence();
            processSequence(getOrganism(bioJavaSequence), bioJavaSequence);
        }

        reader.close();
        fileReader.close();
    } catch (BioException e) {
        throw new BuildException("sequence not in fasta format or wrong alphabet for: " + file, e);
    } catch (NoSuchElementException e) {
        throw new BuildException("no fasta sequences in: " + file, e);
    } catch (FileNotFoundException e) {
        throw new BuildException("problem reading file - file not found: " + file, e);
    } catch (ObjectStoreException e) {
        throw new BuildException("ObjectStore problem while processing: " + file, e);
    } catch (IOException e) {
        throw new BuildException("error while closing FileReader for: " + file, e);
    }
}

From source file:com.freedomotic.plugins.TrackingReadFile.java

/**
 * Reads coordinates from file./*from   w ww  .  j  a v  a2s . co  m*/
 * 
 * @param f file of coordinates 
 */
private void readMoteFileCoordinates(File f) {
    FileReader fr = null;
    ArrayList<Coordinate> coord = new ArrayList<Coordinate>();
    String userId = FilenameUtils.removeExtension(f.getName());

    try {
        LOG.info("Reading coordinates from file {}", f.getAbsolutePath());
        fr = new FileReader(f);

        BufferedReader br = new BufferedReader(fr);
        String line;

        while ((line = br.readLine()) != null) {
            //tokenize string
            StringTokenizer st = new StringTokenizer(line, ",");
            LOG.info("Mote {} coordinate added {}", userId, line);
            Coordinate c = new Coordinate();
            c.setUserId(userId);
            c.setX(new Integer(st.nextToken()));
            c.setY(new Integer(st.nextToken()));
            c.setTime(new Integer(st.nextToken()));
            coord.add(c);
        }
        fr.close();
        WorkerThread wt = new WorkerThread(this, coord, ITERATIONS);
        workers.add(wt);
    } catch (FileNotFoundException ex) {
        LOG.error("Coordinates file not found for mote " + userId);
    } catch (IOException ex) {
        LOG.error("IOException: ", ex);
    } finally {
        try {
            fr.close();
        } catch (IOException ex) {
            LOG.error("IOException: ", ex);
        }
    }
}

From source file:corelyzer.data.CRPreferences.java

public boolean readProperties(final File aFile) {
    try {//  w w w .  ja  v  a  2s  .  c  o m
        FileReader fr = new FileReader(aFile);
        BufferedReader br = new BufferedReader(fr);

        String line;
        while ((line = br.readLine()) != null) {
            String[] toks = line.split("=");

            String key = toks[0].trim();
            String value = toks[1].trim();
            this.setProperty(key, value);
        }

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

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

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

@Override
protected IPluginVersion getInstalledNonOsgiPluginVersion(IPlugin plugin) {
    String versionPath = this.getApplicationContext()
            .getSolutionPath("system/" + plugin.getId() + "/version.xml");
    FileReader reader = null;
    try {//from  w  ww. j av  a2  s.  co m
        File file = new File(versionPath);
        if (!file.exists()) {
            return null;
        }
        reader = new FileReader(versionPath);
        IPluginVersion version = this.getXmlSerializer().getInstalledVersion(new InputSource(reader));
        version.setIsOsgi(false);
        return version;

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

From source file:com.zivacare.android.sdk.ZivaCareConfig.java

/**
 * Use to read the ZivaCareSDK config that is cached
 *
 * @return String / json// w  w  w.j  a  va  2  s. c  om
 * @throws IOException
 */
public String readCacheFile() throws IOException {
    if (!cacheFile.exists())
        return null;
    String strLine = STRING_EMPTY;
    StringBuilder text = new StringBuilder();
    FileReader fReader = null;
    BufferedReader bReader = null;
    try {
        fReader = new FileReader(cacheFile);
        bReader = new BufferedReader(fReader);
        while ((strLine = bReader.readLine()) != null) {
            text.append(strLine + STRING_NEWLINE);
        }
        return text.toString();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bReader != null)
            bReader.close();
        if (fReader != null)
            fReader.close();
    }
    return null;
}

From source file:org.apache.hadoop.mapred.util.ProcfsBasedProcessTree.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  www .j a  v  a2s  .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, String.valueOf(pinfo.getPid()));
        fReader = new FileReader(new File(pidDir, PROCFS_STAT_FILE));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // The process vanished in the interim!
        LOG.warn("The process " + pinfo.getPid() + " may have finished 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), Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)),
                    Integer.parseInt(m.group(5)), Long.parseLong(m.group(7)), Long.parseLong(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;
}