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:br.itecbrazil.serviceftpcliente.model.ThreadEnvio.java

private boolean gravarBackup(File arquivo) {
    logger.info("Gravando backup do arquivo " + arquivo.getName() + ". Thread: "
            + Thread.currentThread().getName());

    String pathDoBackUp = arquivo.getParent().concat(File.separator).concat("backup");
    File diretorio = new File(pathDoBackUp);
    FileReader fr = null;
    BufferedReader br = null;/*from  ww  w . jav  a  2  s  .  c o m*/
    FileWriter fw = null;
    BufferedWriter bw = null;

    try {
        if (!diretorio.exists()) {
            diretorio.mkdir();
        }

        File arquivoBackUp = new File(pathDoBackUp.concat(File.separator).concat(arquivo.getName()));

        fr = new FileReader(arquivo);
        br = new BufferedReader(fr);
        fw = new FileWriter(arquivoBackUp);
        bw = new BufferedWriter(fw);

        String linha = br.readLine();
        while (linha != null) {
            bw.write(linha);
            bw.newLine();
            bw.flush();
            coteudoFileTransfer.append(linha);
            linha = br.readLine();
        }
    } catch (FileNotFoundException ex) {
        loggerExceptionEnvio.info(ex);
        return false;
    } catch (IOException ex) {
        loggerExceptionEnvio.info(ex);
        return false;
    } finally {
        try {
            if (fr != null)
                fr.close();
            if (br != null)
                br.close();
        } catch (IOException ex) {
            loggerExceptionEnvio.info(ex);
            return false;
        }
    }

    return true;
}

From source file:com.ah.ui.actions.home.clientManagement.service.CertificateGenSV.java

public String readFile(String fileName) throws IOException {
    StringBuffer ss = new StringBuffer();
    File file = null;//from  w w  w. j  a v  a  2s  .com
    String strt = "";
    FileReader fr = null;
    BufferedReader bur = null;
    try {
        file = new File(fileName);
        fr = new FileReader(file);
        bur = new BufferedReader(fr);
        bur.readLine();
        while ((strt = bur.readLine()) != null) {
            if (!strt.contains("END CERTIFICATE REQUEST")) {
                ss.append(strt);
            } else {
                return ss.toString();
            }
        }
        bur.close();
        fr.close();
    } catch (Exception e) {
        bur.close();
        fr.close();
        log.error("readFile()", "Try to read file from " + fileName, e);
    }
    return ss.toString();
}

From source file:com.chinamobile.bcbsp.fault.browse.ReadFaultlog.java

/**
 * read fault list from the specific file.
 * @param file/*from ww w .  j  a  va  2  s  .c om*/
 *        fault file to read from.
 * @return fault list.
 */
private List<Fault> readFile(File file) {
    FileReader fr = null;
    try {
        List<Fault> records = new ArrayList<Fault>();
        fr = new FileReader(file);
        br = new BufferedReader(fr);
        String tempRecord = null;
        String[] filds = null;
        while ((tempRecord = br.readLine()) != null) {
            filds = tempRecord.split("--");
            Fault fault = new Fault();
            fault.setTimeOfFailure(filds[0].trim());
            fault.setType(getType(filds[1].trim()));
            fault.setLevel(getLevel(filds[2].trim()));
            fault.setWorkerNodeName(filds[3].trim());
            fault.setJobName((filds[4].trim()));
            fault.setStaffName(filds[5].trim());
            fault.setExceptionMessage(filds[6].trim());
            fault.setFaultStatus(getBoolean(filds[7].trim()));
            records.add(fault);
        }
        br.close();
        fr.close();
        return records;
    } catch (FileNotFoundException e) {
        LOG.error("file not foutnd Exception! ", e);
        return null;
    } catch (IOException e) {
        LOG.error("read file IOExeption! ", e);
        try {
            br.close();
            fr.close();
        } catch (IOException e1) {
            throw new RuntimeException("close file IOException!", e1);
        }
        return null;
    }
}

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

/**
 * Read /proc/cpuinfo, parse and calculate CPU information
 *//* w  w  w. ja va  2 s  .c  om*/
private void readProcCpuInfoFile() {
    // This directory needs to be read only once
    if (readCpuInfoFile) {
        return;
    }
    // Read "/proc/cpuinfo" file
    BufferedReader in = null;
    FileReader fReader = null;
    try {
        fReader = new FileReader(procfsCpuFile);
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        return;
    }
    Matcher mat = null;
    try {
        numProcessors = 0;
        String str = in.readLine();
        while (str != null) {
            mat = PROCESSOR_FORMAT.matcher(str);
            if (mat.find()) {
                numProcessors++;
            }
            mat = FREQUENCY_FORMAT.matcher(str);
            if (mat.find()) {
                cpuFrequency = (long) (Double.parseDouble(mat.group(1)) * 1000); // kHz
            }
            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);
        }
    }
    readCpuInfoFile = true;
}

From source file:com.eviware.soapui.impl.wsdl.WsdlProject.java

private static void normalizeLineBreak(File target, File tmpFile) throws IOException {
    FileReader fr = new FileReader(tmpFile);
    BufferedReader in = new BufferedReader(fr);
    FileWriter fw = new FileWriter(target);
    BufferedWriter out = new BufferedWriter(fw);
    String line = "";
    while ((line = in.readLine()) != null) {
        out.write(line);/*  www.j a va  2  s . c  o  m*/
        out.newLine();
        out.flush();
    }
    out.close();
    fw.close();
    in.close();
    fr.close();
}

From source file:org.apache.ddlutils.io.DatabaseIO.java

/**
 * Reads the database model contained in the specified file.
 * /*  w w  w . j  av a  2 s .c o  m*/
 * @param file The model file
 * @return The database model
 */
public Database read(File file) throws DdlUtilsXMLException {
    FileReader reader = null;

    if (_validateXml) {
        try {
            reader = new FileReader(file);
            new ModelValidator().validate(new StreamSource(reader));
        } catch (IOException ex) {
            throw new DdlUtilsXMLException(ex);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    _log.warn("Could not close reader for file " + file.getAbsolutePath());
                }
                reader = null;
            }
        }
    }

    try {
        reader = new FileReader(file);
        return read(getXMLInputFactory().createXMLStreamReader(reader));
    } catch (XMLStreamException ex) {
        throw new DdlUtilsXMLException(ex);
    } catch (IOException ex) {
        throw new DdlUtilsXMLException(ex);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                _log.warn("Could not close reader for file " + file.getAbsolutePath());
            }
        }
    }
}

From source file:FileViewer.java

/**
 * Load and display the specified file from the specified directory
 *//*from  w  ww.  j  av  a2 s. co  m*/
public void setFile(String directory, String filename) {
    if ((filename == null) || (filename.length() == 0))
        return;
    File f;
    FileReader in = null;
    // Read and display the file contents. Since we're reading text, we
    // use a FileReader instead of a FileInputStream.
    try {
        f = new File(directory, filename); // Create a file object
        in = new FileReader(f); // And a char stream to read it
        char[] buffer = new char[4096]; // Read 4K characters at a time
        int len; // How many chars read each time
        textarea.setText(""); // Clear the text area
        while ((len = in.read(buffer)) != -1) { // Read a batch of chars
            String s = new String(buffer, 0, len); // Convert to a string
            textarea.append(s); // And display them
        }
        this.setTitle("FileViewer: " + filename); // Set the window title
        textarea.setCaretPosition(0); // Go to start of file
    }
    // Display messages if something goes wrong
    catch (IOException e) {
        textarea.setText(e.getClass().getName() + ": " + e.getMessage());
        this.setTitle("FileViewer: " + filename + ": I/O Exception");
    }
    // Always be sure to close the input stream!
    finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
        }
    }
}

From source file:edu.ku.brc.specify.toycode.mexconabio.FileMakerToMySQL.java

/**
 * @param fileName/*from  ww  w. j  a v a 2  s .  c o  m*/
 */
protected void cleanFile(final String fileName) {
    File srcFile = new File(fileName);
    try {
        File destFile = new File("xxx.xml");//File.createTempFile("DB", "xml");
        FileUtils.copyFile(srcFile, destFile);

        //System.out.println("Clean FIle: "+dest)

        FileReader fr = new FileReader(srcFile);
        PrintWriter pw = new PrintWriter(destFile);
        char[] chars = new char[4096 * 8];
        int numChars = fr.read(chars, 0, chars.length);
        while (numChars > 0) {
            for (int i = 0; i < chars.length; i++) {
                //if (chars[i] < 32 || chars[i] > 126)
                if (chars[i] == 0xb) {
                    System.out.println("fixed[" + chars[i] + "]");
                    chars[i] = ' ';

                }
            }
            pw.write(chars, 0, numChars);
            numChars = fr.read(chars, 0, chars.length);
        }

        fr.close();
        pw.close();

        FileUtils.copyFile(destFile, srcFile);

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.google.android.apps.mytracks.TrackListActivity.java

private void checkPriorExceptions(boolean firstTime) {
    final File file = new File(FileUtils.buildExternalDirectoryPath("error.log"));
    if (file != null && file.exists() && file.length() > 0) {
        String msg = getString(R.string.previous_run_crashed);
        Builder builder = new AlertDialog.Builder(TrackListActivity.this);
        // User says no
        builder.setMessage(msg).setNeutralButton(getString(R.string.donot_send_report),
                new DialogInterface.OnClickListener() {
                    @Override/*ww w.  ja v  a2  s  . c o m*/
                    public void onClick(DialogInterface dialog, int which) {
                        // Delete Exceptions File when user presses Ignore
                        if (!file.delete())
                            Toast.makeText(getApplicationContext(), "Exceptions file not deleted",
                                    Toast.LENGTH_LONG).show();
                    }
                });
        // User says yes
        builder.setPositiveButton(R.string.send_report, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_EMAIL, new String[] { Constants.BUGS_MAIL }); //$NON-NLS-1$
                intent.setType("vnd.android.cursor.dir/email"); //$NON-NLS-1$
                intent.putExtra(Intent.EXTRA_SUBJECT, "nogago Tracks bug"); //$NON-NLS-1$
                StringBuilder text = new StringBuilder();
                text.append("\nDevice : ").append(Build.DEVICE); //$NON-NLS-1$
                text.append("\nBrand : ").append(Build.BRAND); //$NON-NLS-1$
                text.append("\nModel : ").append(Build.MODEL); //$NON-NLS-1$
                text.append("\nProduct : ").append("Tracks"); //$NON-NLS-1$
                text.append("\nBuild : ").append(Build.DISPLAY); //$NON-NLS-1$
                text.append("\nVersion : ").append(Build.VERSION.RELEASE); //$NON-NLS-1$
                text.append("\nApp Starts : ").append(EulaUtils.getAppStart(TrackListActivity.this)); //$NON-NLS-1$

                try {
                    PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
                    if (info != null) {
                        text.append("\nApk Version : ").append(info.versionName).append(" ") //$NON-NLS-1$//$NON-NLS-2$
                                .append(info.versionCode);
                    }
                } catch (NameNotFoundException e) {
                }

                try {
                    FileReader fr = new FileReader(file);
                    BufferedReader br = new BufferedReader(fr);
                    String line;
                    while (br.read() != -1) {
                        if ((line = br.readLine()) != null) {
                            text.append(line);
                        }
                    }
                    br.close();
                    fr.close();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "Error reading exceptions file!", Toast.LENGTH_LONG)
                            .show();
                }
                intent.putExtra(Intent.EXTRA_TEXT, text.toString());
                startActivity(Intent.createChooser(intent, getString(R.string.send_report)));

                if (!file.delete())
                    Toast.makeText(getApplicationContext(), "Exceptions file not deleted", Toast.LENGTH_LONG)
                            .show();
            }

        });
        builder.show();
    }
}

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

/**
 * Read /proc/stat file, parse and calculate cumulative CPU
 *//*from  ww w  .ja  v  a2 s. co  m*/
private void readProcStatFile() {
    // Read "/proc/stat" file
    BufferedReader in = null;
    FileReader fReader = null;
    try {
        fReader = new FileReader(procfsStatFile);
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        return;
    }

    Matcher mat = null;
    try {
        String str = in.readLine();
        while (str != null) {
            mat = CPU_TIME_FORMAT.matcher(str);
            if (mat.find()) {
                long uTime = Long.parseLong(mat.group(1));
                long nTime = Long.parseLong(mat.group(2));
                long sTime = Long.parseLong(mat.group(3));
                cumulativeCpuTime = uTime + nTime + sTime; // milliseconds
                break;
            }
            str = in.readLine();
        }
        cumulativeCpuTime *= jiffyLengthInMillis;
    } 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);
        }
    }
}