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:org.apache.vxquery.xtest.TestCaseResult.java

private String slurpFile(File f) {
    StringWriter out = new StringWriter();
    try {/*from   w w w. ja va 2s .c  om*/
        FileReader in = new FileReader(f);
        try {
            char[] buffer = new char[8192];
            int c;
            while ((c = in.read(buffer)) >= 0) {
                out.write(buffer, 0, c);
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    } catch (IOException e) {
        return null;
    }
    return out.toString();
}

From source file:main.server.SourceBrowserDataProvider.java

private String readFile(File file) throws IOException {
    StringBuffer buf = new StringBuffer();
    char[] a = new char[4096];
    FileReader r = null;
    try {/*from  w  ww.j a  v  a2 s.com*/
        r = new FileReader(file);
        for (;;) {
            int sz = r.read(a);
            if (sz < 0) {
                break;
            }
            buf.append(a, 0, sz);
        }
    } finally {
        if (r != null) {
            try {
                r.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return buf.toString();
}

From source file:at.tuwien.minimee.migration.parser.TIME_Parser.java

public void parse(String fileName) {

    FileReader fileReader = null;
    try {/*from   w w w. j  ava  2  s  .  c  o  m*/
        fileReader = new FileReader(fileName);
        try {
            BufferedReader input = new BufferedReader(fileReader);

            // the output file shall only have one line
            String line;
            while ((line = input.readLine()) != null) {
                parseLine(line);
            }
        } finally {
            fileReader.close();
        }
    } catch (IOException e) {
        log.error(e);
    }
}

From source file:it.txt.ens.client.publisher.impl.osgi.test.BasicENSPublisherTest.java

@Test
public void testUseOfBasicENSSubscriber() throws Exception {
    Thread.currentThread().setContextClassLoader(BasicENSPublisherTest.class.getClassLoader());

    assertNotNull("The bundle context is null", context);

    File propertiesFile = new File(PROPERTIES_RELATIVE_PATH);
    FileReader reader = null;
    Properties properties = new Properties();
    try {/*from w  w  w . ja va 2s.c  o  m*/
        reader = new FileReader(propertiesFile);
        properties.load(reader);
        reader.close();
    } catch (FileNotFoundException e) {
        //            if (LOGGER.isLoggable(Level.SEVERE))
        //                LOGGER.log(Level.SEVERE, MessageFormat.format(LOG_MESSAGES.getString("propertyFile.notFound"), 
        //                        propertiesFile.getAbsolutePath()), e);
        System.out.println("Properties file not found. File: " + propertiesFile.getAbsolutePath());
        e.printStackTrace();
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e) {
            }
    }

    //add implementation ID
    properties.setProperty(FilterAttributes.PUBLISHER_IMPLEMENTATION_KEY,
            BasicENSPublisherMSF.IMPLEMENTATION_ID);
    //add ownership id
    properties.setProperty(FilterAttributes.PUBLISHER_OWNER_KEY,
            String.valueOf(context.getBundle().getBundleId()));

    //retrieve the configuration admin service
    ServiceReference<ConfigurationAdmin> configAdminSR = context.getServiceReference(ConfigurationAdmin.class);
    ConfigurationAdmin configAdmin = context.getService(configAdminSR);
    Configuration config = configAdmin
            .createFactoryConfiguration(RegisteredServices.PUBLISHER_MANAGED_SERVICE_FACTORY_PID, null);
    config.update(MapConverter.convert(properties));
    context.ungetService(configAdminSR);

    //
    Collection<ServiceReference<ENSPublisher>> references = null;
    EqualsFilter implementationFilter = new EqualsFilter(FilterAttributes.PUBLISHER_IMPLEMENTATION_KEY,
            BasicENSPublisherMSF.IMPLEMENTATION_ID);
    EqualsFilter ownershipFilter = new EqualsFilter(FilterAttributes.PUBLISHER_OWNER_KEY,
            String.valueOf(context.getBundle().getBundleId()));
    AndFilter and = new AndFilter().and(implementationFilter).and(ownershipFilter);
    String serviceRegistryFilter = and.toString();
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Filtering OSGi service registry with query " + serviceRegistryFilter
                + ". Class: " + ENSPublisher.class.getName());
    }
    int i = 0;
    //FIXME add a timeout otherwise we could wait forever! (aspitt semb!)
    long startTime = System.currentTimeMillis();
    do {
        i++;
        references = context.getServiceReferences(ENSPublisher.class, serviceRegistryFilter);
        Thread.sleep(100);
    } while (references.isEmpty() && (System.currentTimeMillis() - startTime) <= TIMEOUT);
    System.out.println("Cycle counter " + i);

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Count of services found: " + references.size());
    }
    assertEquals("Bad count of " + ENSPublisher.class.getName() + " found.", 1, references.size());

    ServiceReference<ENSPublisher> serviceRef = references.iterator().next();
    //        ServiceReference<ENSSubscriber> serviceRef = context.getServiceReference(ENSSubscriber.class);
    assertNotNull("The service reference is null", serviceRef);
    //        System.out.println("SERVICE REFERENCE PROPERTIES");
    //        for (String key : serviceRef.getPropertyKeys())
    //            System.out.println(key + ": " + serviceRef.getProperty(key));

    publisher = context.getService(serviceRef);
    assertNotNull("The publisher is null", publisher);

    ServiceReference<ENSEventFactory> eventFactorySR = context.getServiceReference(ENSEventFactory.class);
    assertNotNull("The service reference for the event factory is null", eventFactorySR);
    eventFactory = context.getService(eventFactorySR);
    assertNotNull("The the event factory is null", eventFactory);

    publisher.connect();
    for (int j = 0; j < 100; j++) {
        publishEvent("Message " + (j + 1));
        Thread.sleep(100);
    }
    publisher.disconnect();

    context.ungetService(serviceRef);
}

From source file:org.aksw.sparqlify.qa.metrics.understandability.SoundingUri.java

private void initTrigramStats(String wordlistFilePath) throws IOException {
    trigramStats = new HashMap<String, Integer>();
    numTrigrams = 0;/*from   ww  w .j  a  va  2 s.com*/

    FileReader fReader = new FileReader(wordlistFilePath);
    BufferedReader bReader = new BufferedReader(fReader);

    String lineBuff = "";

    while ((lineBuff = bReader.readLine()) != null) {
        updateTrigramStats(lineBuff);
    }

    bReader.close();
    fReader.close();
}

From source file:com.amazonaws.mturk.cmd.MakeTemplate.java

private void copyTemplateFile(String sourceRoot, String targetRoot, String extension) throws Exception {
    String inputFileName = sourceRoot + extension;
    String outputFileName = targetRoot + extension;

    System.out.println("Copying resource file: " + outputFileName);

    File inputFile = new File(inputFileName);
    if (!inputFile.exists() || !inputFile.canRead()) {
        throw new Exception("Could not read from the file " + inputFileName);
    }/*from  w w  w.  j av  a2  s .  c  o m*/

    File outputFile = new File(outputFileName);
    if (!outputFile.exists()) {
        if (!outputFile.createNewFile() || !outputFile.canWrite())
            throw new Exception("Could not write to the file " + outputFileName);
    }

    // copy file
    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);

    try {
        char[] buffer = new char[1024];
        int nread = 0;
        while ((nread = in.read(buffer)) != -1) {
            out.write(buffer, 0, nread);
        }
    } finally {
        in.close();
        out.close();
    }
}

From source file:org.apache.velocity.test.sql.HsqlDB.java

private String getFileContents(String fileName) throws Exception {
    FileReader fr = null;

    try {/*from   w  w  w  .j av a 2  s.  c o  m*/
        fr = new FileReader(fileName);

        char[] fileBuf = new char[1024];
        StringBuffer sb = new StringBuffer(1000);
        int res = -1;

        while ((res = fr.read(fileBuf, 0, 1024)) > -1) {
            sb.append(fileBuf, 0, res);
        }

        return sb.toString();
    } finally {

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

From source file:net.doubledoordev.backend.util.Settings.java

private Settings() throws IOException {
    try {/*  w ww . ja  v a  2 s .  c  om*/
        FileReader fileReader;

        if (SERVERS_FILE.exists()) {
            fileReader = new FileReader(SERVERS_FILE);
            if (SERVERS_FILE.exists()) {
                for (Server server : GSON.fromJson(fileReader, Server[].class)) {
                    servers.put(server.getID(), server);
                }
            }
            fileReader.close();
        }

        if (USERS_FILE.exists()) {
            fileReader = new FileReader(USERS_FILE);
            if (USERS_FILE.exists()) {
                for (User user : GSON.fromJson(fileReader, User[].class)) {
                    users.put(user.getUsername().toLowerCase(), user);
                }
            }
            fileReader.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jlibrary.client.ui.history.HistoryBook.java

private static HistoryBook initHistoryBook() throws ConfigException {

    // Load history from disk
    String home = JLibraryProperties.getProperty(JLibraryProperties.JLIBRARY_HOME);
    File f = new File(home, ".jlibrary");
    f.mkdirs();/*from  w  ww . j  a  v a2  s  .  c  om*/
    if (!f.exists()) {
        throw new ConfigException(".jlibrary directory don't found");
    }
    XStream xstream = new XStream();
    ClassLoader clientClassLoader = JLibraryPlugin.getDefault().getClass().getClassLoader();
    xstream.setClassLoader(clientClassLoader);

    File file = null;
    FileReader reader = null;
    try {
        file = new File(f, ".history-registry.xml");
        if (!file.exists()) {
            instance = new HistoryBook().createHistoryBook();
            instance.saveHistory();
            return instance;
        }
        reader = new FileReader(file);
        instance = (HistoryBook) xstream.fromXML(reader);
        instance.updateDates();
        return instance;
    } catch (Exception e) {
        // Backup the corrupted file and remove it
        String backupName = file.getName();
        String extension = FileUtils.getExtension(file.getName());
        backupName = StringUtils.replace(backupName, extension, "");
        backupName += new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".bak";
        File backupFile = new File(backupName);
        try {
            org.apache.commons.io.FileUtils.copyFile(file, backupFile);
            file.delete();
        } catch (IOException e1) {
            logger.error(e1.getMessage(), e);
        }
        throw new ConfigException(e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:nz.co.fortytwo.freeboard.server.util.ChartProcessor.java

/**
 * Reads the .kap file, and the generated tilesresource.xml to get
 * chart desc, bounding box, and zoom levels 
 * @param chartFile// w w w  . j  a  va  2  s . c  o m
 * @throws Exception
 */
public void processKapChart(File chartFile, boolean reTile) throws Exception {
    String chartName = chartFile.getName();
    chartName = chartName.substring(0, chartName.lastIndexOf("."));
    File dir = new File(chartFile.getParentFile(), chartName);
    if (manager) {
        System.out.print("Chart tag:" + chartName + "\n");
        System.out.print("Chart dir:" + dir.getPath() + "\n");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Chart tag:" + chartName);
        logger.debug("Chart dir:" + dir.getPath());
    }
    //start by running the gdal scripts
    if (reTile) {
        executeGdal(chartFile, chartName,
                //this was for NZ KAP charts
                //Arrays.asList("gdal_translate", "-if","GTiff", "-of", "vrt", "-expand", "rgba",chartFile.getName(),"temp.vrt"),
                //this for US NOAA charts
                Arrays.asList("gdal_translate", "-of", "vrt", "-expand", "rgba", chartFile.getName(),
                        "temp.vrt"),
                Arrays.asList("gdal2tiles.py", "temp.vrt", chartName));
    }
    //now get the Chart Name from the kap file
    FileReader fileReader = new FileReader(chartFile);
    char[] chars = new char[4096];
    fileReader.read(chars);
    fileReader.close();
    String header = new String(chars);
    int pos = header.indexOf("BSB/NA=") + 7;
    String desc = header.substring(pos, header.indexOf("\n", pos)).trim();
    //if(desc.endsWith("\n"))desc=desc.substring(0,desc.length()-1);
    if (logger.isDebugEnabled())
        logger.debug("Name:" + desc);
    //we cant have + or , or = in name, as its used in storing ChartplotterViewModel
    //US50_2 BERING SEA CONTINUATION,NU=2401,RA=2746,3798,DU=254
    desc = desc.replaceAll("\\+", " ");
    desc = desc.replaceAll(",", " ");
    desc = desc.replaceAll("=", "/");
    //limit length too
    if (desc.length() > 40) {
        desc = desc.substring(0, 40);
    }
    //process the layer data

    //read data from dirName/tilelayers.xml
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File(dir, "tilemapresource.xml"));
    //we need BoundingBox
    Element box = (Element) document.selectSingleNode("//BoundingBox");
    String minx = box.attribute("minx").getValue();
    String miny = box.attribute("miny").getValue();
    String maxx = box.attribute("maxx").getValue();
    String maxy = box.attribute("maxy").getValue();
    if (manager) {
        System.out.print("Box:" + minx + "," + miny + "," + maxx + "," + maxy + "\n");
    }
    if (logger.isDebugEnabled())
        logger.debug("Box:" + minx + "," + miny + "," + maxx + "," + maxy);

    //we need TileSets, each tileset has an href, we need first and last for zooms
    @SuppressWarnings("unchecked")
    List<Attribute> list = document.selectNodes("//TileSets/TileSet/@href");
    int minZoom = 18;
    int maxZoom = 0;
    for (Attribute attribute : list) {
        int zoom = Integer.valueOf(attribute.getValue());
        if (zoom < minZoom)
            minZoom = zoom;
        if (zoom > maxZoom)
            maxZoom = zoom;
    }
    if (manager) {
        System.out.print("Zoom:" + minZoom + "-" + maxZoom + "\n");
    }
    if (logger.isDebugEnabled())
        logger.debug("Zoom:" + minZoom + "-" + maxZoom);

    String snippet = "\n\tvar " + chartName + " = L.tileLayer(\"http://{s}.{server}:8080/mapcache/" + chartName
            + "/{z}/{x}/{y}.png\", {\n" + "\t\tserver: host,\n" + "\t\tsubdomains: 'abcd',\n"
            + "\t\tattribution: '" + chartName + " " + desc + "',\n" + "\t\tminZoom: " + minZoom + ",\n"
            + "\t\tmaxZoom: " + maxZoom + ",\n" + "\t\ttms: true\n" + "\t\t}).addTo(map);\n";

    if (manager) {
        System.out.print(snippet + "\n");
    }
    if (logger.isDebugEnabled())
        logger.debug(snippet);
    //add it to local freeboard.txt
    File layers = new File(dir, "freeboard.txt");
    FileUtils.writeStringToFile(layers, snippet);
    //now zip the result
    System.out.print("Zipping directory...\n");
    ZipUtils.zip(dir, new File(dir.getParentFile(), chartName + ".zip"));
    System.out.print("Zipping directory complete, in "
            + new File(dir.getParentFile(), chartName + ".zip").getAbsolutePath() + "\n");
    System.out.print("Conversion of " + chartName + " was completed successfully!\n");
}