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:citation_prediction.CitationCore.java

/**
 * Get CSV citation history from a file.
 * //from  w  w w.ja v  a  2 s  .  c  o  m
 * @param filename The filename and path containing the citation data.
 * @param format The format of the file.
 * @param hasHeader Does the file have a line with headings?
 * @return A record containing the csv information.
 */
private static List<CSVRecord> getCSVData(String filename, CSVFormat format, boolean hasHeader) {

    boolean error = true;
    List<CSVRecord> list_ourdata = null;

    try {
        FileReader ourdata = new FileReader(filename);

        CSVParser data_parser = new CSVParser(ourdata, format);

        list_ourdata = data_parser.getRecords();

        if (hasHeader) {
            list_ourdata.remove(0);
        } //remove header file.

        Iterator<CSVRecord> list_iterator = list_ourdata.iterator();
        for (int rowIndex = 0; rowIndex < list_ourdata.size(); rowIndex++) {
            CSVRecord record = list_iterator.next();

            System.out.println("#" + (rowIndex + 1) + " " + record.toString());

        }

        data_parser.close();
        ourdata.close();

        error = false;

    } catch (java.io.FileNotFoundException e) {
        System.err.println("ERROR: There was an error opening, reading, or parsing the input file.");
        System.err.println("ERROR:" + filename);
        error = true;
    } catch (java.io.IOException e) {
        System.err.println("ERROR: Could not close the parser or the input file.");
        error = true;
    }

    if (error || list_ourdata == null) {
        System.exit(1);
        return null;
    } else {
        return list_ourdata;
    }
}

From source file:de.peterspan.csv2db.converter.AbstractConverter.java

protected List<String[]> readFile() throws Exception {
    FileReader fileReader = null;
    CSVReader csvReader = null;//  w  w  w . j  a  v  a 2s  .c o  m
    List<String[]> allLines = new ArrayList<String[]>();
    try {
        fileReader = new FileReader(inputFile);
        csvReader = new CSVReader(fileReader, ';');
        allLines = csvReader.readAll();
    } catch (IOException ioe) {
        log.error("An error occured while trying to read the input file.", ioe);
    } finally {
        if (csvReader != null)
            csvReader.close();
        if (fileReader != null)
            fileReader.close();
    }

    firePropertyChange("readingLines", false, true);

    return allLines;
}

From source file:JsonParser.ParseJson.java

public void jsonParse(String filePath) {

    FileReader fr = null;
    try {/*  www.  j av a  2 s  .  c  o  m*/
        JsonParser parser = new JsonParser();
        fr = new FileReader(filePath);

        JsonElement data = parser.parse(fr);
        //parseJson(data);
        dumpJSONElement(data, "");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ParseJson.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fr.close();
        } catch (IOException ex) {
            Logger.getLogger(ParseJson.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.apache.wsrp4j.persistence.xml.driver.PersistentHandlerImpl.java

/**
 * Restore all known XML files from the persistent store into the
 * PersistentDataObject. The class type, which is part of the filename
 * is stored in the PersistentInformation object of the
 * PersistentDataObject./*from   w w w  . j a  v a2 s. c  o m*/
 *
 * @param persistentDataObject
 * @return PersistentDataObject
 *
 * @throws WSRPException
 */
public PersistentDataObject restoreMultiple(PersistentDataObject persistentDataObject) throws WSRPException {

    String MN = "restoreMultiple";

    if (log.isDebugEnabled()) {
        log.debug(Utility.strEnter(MN));
    }

    Mapping mapping = null;
    Unmarshaller unmarshaller = null;

    try {

        PersistentInformationXML persistentInformation = (PersistentInformationXML) persistentDataObject
                .getPersistentInformation();

        if (persistentInformation.getMappingFileName() != null) {

            mapping = new Mapping();
            mapping.loadMapping(persistentInformation.getMappingFileName());
            unmarshaller = new Unmarshaller(mapping);
        }

        File file = new File(persistentInformation.getStoreDirectory());

        if (file.exists()) {

            File[] files = file.listFiles();

            for (int x = 0; x < files.length; x++) {

                if (files[x].isFile()) {

                    String currentFileName = files[x].getName();
                    // check for valid xml file
                    if (currentFileName.endsWith(persistentInformation.getExtension())) {

                        // check for valid object
                        if (currentFileName.startsWith(persistentInformation.getFilenameStub())) {
                            // load object
                            try {

                                FileReader fileReader = new FileReader(files[x]);

                                ((PersistentDataObjectXML) persistentDataObject).unMarshalFile(fileReader,
                                        unmarshaller);

                                fileReader.close();

                                Object o = persistentDataObject.getLastElement();
                                int hashCode = o.hashCode();
                                String code = new Integer(hashCode).toString();
                                _filenameMap.put(code, files[x].getAbsolutePath());

                                if (log.isDebugEnabled()) {
                                    log.debug("File: " + files[x].getAbsolutePath() + " added with hashCode = "
                                            + code);
                                }

                            } catch (Exception e) {

                                // restore error
                                WSRPXHelper.throwX(log, ErrorCodes.RESTORE_OBJECT_ERROR, e);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        // restore error
        WSRPXHelper.throwX(log, ErrorCodes.RESTORE_OBJECT_ERROR, e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Utility.strExit(MN));
    }

    return persistentDataObject;

}

From source file:br.ufjf.taverna.core.TavernaClientBase.java

protected HttpURLConnection request(String endpoint, TavernaServerMethods method, int expectedResponseCode,
        String acceptData, String contentType, String filePath, String putData) throws TavernaException {
    HttpURLConnection connection = null;

    try {//from   ww  w.  j  a v a  2s.c  o  m
        String uri = this.getBaseUri() + endpoint;
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        String authorization = this.username + ":" + this.password;
        String encodedAuthorization = "Basic " + new String(Base64.encodeBase64(authorization.getBytes()));
        connection.setRequestProperty("Authorization", encodedAuthorization);
        connection.setRequestMethod(method.getMethod());

        if (acceptData != null) {
            connection.setRequestProperty("Accept", acceptData);
        }

        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }

        if (TavernaServerMethods.GET.equals(method)) {

        } else if (TavernaServerMethods.POST.equals(method)) {
            FileReader fr = new FileReader(filePath);
            char[] buffer = new char[1024 * 10];
            int read;
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            while ((read = fr.read(buffer)) != -1) {
                writer.write(buffer, 0, read);
            }
            writer.flush();
            writer.close();
            fr.close();
        } else if (TavernaServerMethods.PUT.equals(method)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(putData);
            writer.flush();
            writer.close();
        } else if (TavernaServerMethods.DELETE.equals(method)) {

        }

        int responseCode = connection.getResponseCode();
        if (responseCode != expectedResponseCode) {
            throw new TavernaException(
                    String.format("Invalid HTTP Response Code. Expected %d, actual %d, URL %s",
                            expectedResponseCode, responseCode, url));
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return connection;
}

From source file:com.appeligo.showfiles.ShowFile.java

/**
 * @param request//from w  ww  .  j a  va  2s .c  o  m
 * @param out
 * @param filename
 * @throws IOException
 * @throws FileNotFoundException
 */
private void showPreview(HttpServletRequest request, PrintWriter out, String path, String filename) {

    if (filename.endsWith("/")) {
        filename = filename.substring(0, filename.length() - 1);
    }

    int lastslash = filename.lastIndexOf('/');
    int comma = filename.lastIndexOf(',');
    int minus = filename.lastIndexOf('-');
    int dot = filename.lastIndexOf('.');

    String programID = filename.substring(lastslash + 1, comma);

    long clipStartSecs = 0;
    long clipLengthSecs = 0;
    try {
        clipStartSecs = Long.parseLong(filename.substring(comma + 1, minus));
        clipLengthSecs = Long.parseLong(filename.substring(minus + 1, dot));
    } catch (NumberFormatException e) {
        log.error("Can't parse the filename into a start time!", e);
        throw e;
    } catch (StringIndexOutOfBoundsException e) {
        log.error("Can't parse the filename for preview time info", e);
        throw e;
    }

    out.println("<a href=\"" + request.getContextPath() + "/ShowFlv" + path + filename + "?start=" + 0
            + "&duration=" + clipLengthSecs + "\">" + "<img src=\"" + request.getContextPath()
            + "/skins/default/videoIcon.gif\" alt=\"video\"/>" + (clipStartSecs / 60) + ":"
            + String.format("%02d", (clipStartSecs % 60)) + "</a>");

    File titleFile = new File(documentRoot + path + programID + ".title");
    if (titleFile.exists()) {
        try {
            FileReader titleReader = new FileReader(titleFile);
            BufferedReader lineReader = new BufferedReader(titleReader);
            out.println(" " + lineReader.readLine());
            titleReader.close();
        } catch (IOException e) {
            out.println("(Error reading title file) " + e.getMessage());
        }
    }
}

From source file:org.deri.iris.performance.IRISPerformanceTest.java

/**
 * Loads the content of a file as a string.
 * @param filename the file name.//from  www.  j a  va 2  s  . c  o  m
 * @return a string representing the file content.
 */
private String loadFile(final String filename) {
    FileReader r = null;
    StringBuilder builder = null;
    try {
        r = new FileReader(filename);
        builder = new StringBuilder();

        int ch = -1;
        while ((ch = r.read()) >= 0) {
            builder.append((char) ch);
        }
        r.close();
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    }

    return builder.toString();
}

From source file:com.amalto.workbench.editors.XSDDriver.java

public String outputXSD() {
    StringBuffer buffer = new StringBuffer();
    FileReader reader;
    try {/*from   w ww. j  a v a2 s  .co m*/
        reader = new FileReader(outPut);
        BufferedReader bufferedReader = new BufferedReader(reader);

        String nextLine = bufferedReader.readLine();
        while (nextLine != null) {
            buffer.append(nextLine);
            buffer.append("\r\n");//$NON-NLS-1$
            nextLine = bufferedReader.readLine();
        }
        reader.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        log.error(e.getMessage(), e);
    } finally {
        boolean result = false;
        int tryCount = 0;
        while (!result && tryCount++ < 10) {
            System.gc();
            result = delete(outPut);
        }
    }

    return buffer.toString();
}

From source file:org.jaggeryjs.jaggery.tools.JaggeryShell.java

/**
 * Evaluate JavaScript source.//from   w ww.  ja  va2 s .c om
 *
 * @param cx the current context
 * @param filename the name of the file to compile, or null
 *                 for interactive mode.
 */
@SuppressWarnings("unused")
private void processSource(Context cx, String filename) {
    if (filename == null) {
        processSource(cx);
    } else {

        final String fileSeparator = System.getProperty("file.separator");
        String fileToProcess = filename.replace("\\", fileSeparator + fileSeparator);
        fileToProcess = fileToProcess.replace("/", fileSeparator + fileSeparator);

        FileReader in = null;
        try {
            in = new FileReader(fileToProcess);
            in.toString();
        } catch (FileNotFoundException ex) {
            Context.reportError("Couldn't open file \"" + fileToProcess + "\".");
            return;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                LOG.error("Error closing file reader for file " + filename, e);
            }

        }

        CommandLineExecutor.parseJaggeryScript(fileToProcess);
    }
}