Example usage for java.io Reader close

List of usage examples for java.io Reader close

Introduction

In this page you can find the example usage for java.io Reader close.

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:magixcel.FileMan.java

public static boolean getLinesFromFile() {
    InputStream inputStream = null;
    Reader reader = null;
    BufferedReader bufferedReader = null;

    try {/*w  w  w  .ja v a  2  s .c o m*/
        inputStream = new FileInputStream(INPUT_FILE_PATH);
        reader = new InputStreamReader(inputStream, Charsets.ISO_8859_1);
        bufferedReader = new BufferedReader(reader);

        String line = bufferedReader.readLine();
        while (line != null && line.length() > 0) {
            LINES_FROM_INPUT_FILE.add(line);
            line = bufferedReader.readLine();
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(FileMan.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(FileMan.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } finally {
        try {
            inputStream.close();
            reader.close();
            bufferedReader.close();
        } catch (IOException ex) {
            Logger.getLogger(FileMan.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return true;
}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getLycancoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    try {//w w  w .ja v a  2s. c om
        String currencies[] = { "USD", "EUR" };
        String urls[] = { "https://btc-e.com/api/2/btc_usd/ticker", "https://btc-e.com/api/2/btc_eur/ticker" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                JSONObject ticker = head.getJSONObject("ticker");
                Double avg = ticker.getDouble("avg") * LycBtcRate;
                String euros = String.format("%.8f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros),
                        "cryptsy.com and " + URL.getHost()));
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.feathercoin.wallet.feathercoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getFeathercoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;//from   w  ww  .j a v  a2  s.c om
    try {
        /*          String currencies[] = {"USD", "BTC", "RUR"};
                    String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker"};
                    for(int i = 0; i < currencies.length; ++i) {
        final String currencyCode = currencies[i];
        final URL URL = new URL(urls[i]);
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();
                
        Reader reader = null;
        try
        {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            String euros = String.format("%.4f", avg);
            // Fix things like 3,1250
            euros = euros.replace(",", ".");
            rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
            if(currencyCode.equalsIgnoreCase("BTC")) btcRate = avg;
        }
        finally
        {
            if (reader != null)
                reader.close();
        }
                    }*/
        // Handle FTC/USD special since we have to do maths
        URL URL = null;
        try {
            URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is feathercoins priced in bitcoins
            btcRate = avg;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle FTC/USD special since we have to do maths
        URL = null;
        URL = new URL("https://btc-e.com/api/2/btc_usd/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in dollars.  We want FTC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle FTC/BTC special since we have to do maths
        URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want FTC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:edu.uci.ics.jung.io.PartitionDecorationReader.java

/**
 * Decorates vertices in the specified partition with strings. The
 * decorations are specified by a text file with the following format:
 * /*w  w w. j a  va 2  s. c  o  m*/
 * <pre>
 * vid_1 label_1 
 * vid_2 label_2 ...
 * </pre>
 * 
 * <p>
 * The strings must be unique within this partition; duplicate strings will
 * cause a <code>UniqueLabelException</code> to be thrown.
 * 
 * <p>
 * The end of the file may be artificially set by putting the string <code>end_of_file</code>
 * on a line by itself.
 * </p>
 * 
 * @param bg
 *            the bipartite graph whose vertices are to be decorated
 * @param name_reader
 *            the reader containing the decoration information
 * @param partition
 *            the vertex partition whose decorations are specified by this
 *            file
 * @param string_key
 *            the user data key for the decorations created
 */
public static void loadStrings(Graph bg, Reader name_reader, Predicate partition, Object string_key) {
    StringLabeller id_label = StringLabeller.getLabeller(bg, partition);
    StringLabeller string_label = StringLabeller.getLabeller(bg, string_key);
    try {
        BufferedReader br = new BufferedReader(name_reader);
        while (br.ready()) {
            String curLine = br.readLine();
            if (curLine == null || curLine.equals("end_of_file"))
                break;
            if (curLine.trim().length() == 0)
                continue;
            String[] parts = curLine.trim().split("\\s+", 2);

            Vertex v = id_label.getVertex(parts[0]);
            if (v == null)
                throw new FatalException("Invalid vertex label");

            // attach the string to this vertex
            string_label.setLabel(v, parts[1]);
        }
        br.close();
        name_reader.close();
    } catch (IOException ioe) {
        throw new FatalException("Error loading names from reader " + name_reader, ioe);
    } catch (UniqueLabelException ule) {
        throw new FatalException("Unexpected duplicate name in reader " + name_reader, ule);
    }
}

From source file:de.schildbach.wallet.worldcoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getworldcoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;/*  w w  w.  j av a 2s.c  o m*/
    try {
        /*          String currencies[] = {"USD", "BTC", "RUR"};
                    String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker"};
                    for(int i = 0; i < currencies.length; ++i) {
        final String currencyCode = currencies[i];
        final URL URL = new URL(urls[i]);
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();
                
        Reader reader = null;
        try
        {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            String euros = String.format("%.4f", avg);
            // Fix things like 3,1250
            euros = euros.replace(",", ".");
            rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
            if(currencyCode.equalsIgnoreCase("BTC")) btcRate = avg;
        }
        finally
        {
            if (reader != null)
                reader.close();
        }
                    }*/
        // Handle WDC/USD special since we have to do maths
        URL URL = null;
        try {
            URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is worldcoins priced in bitcoins
            btcRate = avg;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle WDC/USD special since we have to do maths
        URL = null;
        URL = new URL("https://btc-e.com/api/2/btc_usd/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in dollars.  We want WDC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle WDC/BTC special since we have to do maths
        URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want FTC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.springrts.springls.CmdLineArgs.java

/**
 * Processes all command line arguments in 'args'.
 * Raises an exception in case of errors.
 * @return whether to exit the application after this method
 *//*from w  ww. j  a v  a2s  .  co m*/
private static boolean apply(Configuration configuration, CommandLineParser parser, Options options,
        String[] args) throws ParseException {
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.getApplicationName(), options);
        return true;
    }

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue("port");
        int port = Integer.parseInt(portStr);
        if ((port < 1) || (port > 65535)) {
            throw new ParseException("Invalid port specified: " + portStr);
        }
        configuration.setProperty(ServerConfiguration.PORT, port);
    }
    if (cmd.hasOption("database")) {
        configuration.setProperty(ServerConfiguration.USE_DATABASE, true);
    } else if (cmd.hasOption("file-storage")) {
        configuration.setProperty(ServerConfiguration.USE_DATABASE, false);
    } else {
        configuration.setProperty(ServerConfiguration.LAN_MODE, true);
    }
    if (cmd.hasOption("statistics")) {
        configuration.setProperty(ServerConfiguration.STATISTICS_STORE, true);
    }
    if (cmd.hasOption("nat-port")) {
        String portStr = cmd.getOptionValue("port");
        int port = Integer.parseInt(portStr);
        if ((port < 1) || (port > 65535)) {
            throw new ParseException("Invalid NAT traversal port" + " specified: " + portStr);
        }
        configuration.setProperty(ServerConfiguration.NAT_PORT, port);
    }
    if (cmd.hasOption("log-main")) {
        configuration.setProperty(ServerConfiguration.CHANNELS_LOG_REGEX, "^main$");
    }
    if (cmd.hasOption("lan-admin")) {
        String[] usernamePassword = cmd.getOptionValues("lan-admin");

        if (usernamePassword.length < 1) {
            throw new MissingArgumentException("LAN admin user name is missing");
        }
        String username = usernamePassword[0];
        String password = (usernamePassword.length > 1) ? usernamePassword[0]
                : ServerConfiguration.getDefaults().getString(ServerConfiguration.LAN_ADMIN_PASSWORD);

        String error = Account.isOldUsernameValid(username);
        if (error != null) {
            throw new ParseException("LAN admin user name is not valid: " + error);
        }
        error = Account.isPasswordValid(password);
        if (error != null) {
            throw new ParseException("LAN admin password is not valid: " + error);
        }
        configuration.setProperty(ServerConfiguration.LAN_ADMIN_USERNAME, username);
        configuration.setProperty(ServerConfiguration.LAN_ADMIN_PASSWORD, password);
    }
    if (cmd.hasOption("load-args")) {
        File argsFile = new File(cmd.getOptionValue("load-args"));
        Reader inF = null;
        BufferedReader in = null;
        try {
            try {
                inF = new FileReader(argsFile);
                in = new BufferedReader(inF);
                String line;
                List<String> argsList = new LinkedList<String>();
                while ((line = in.readLine()) != null) {
                    String[] argsLine = line.split("[ \t]+");
                    argsList.addAll(Arrays.asList(argsLine));
                }
                String[] args2 = argsList.toArray(new String[argsList.size()]);
                apply(configuration, parser, options, args2);
            } finally {
                if (in != null) {
                    in.close();
                } else if (inF != null) {
                    inF.close();
                }
            }
        } catch (Exception ex) {
            throw new ParseException("invalid load-args argument: " + ex.getMessage());
        }
    }
    if (cmd.hasOption("spring-version")) {
        String version = cmd.getOptionValue("spring-version");
        configuration.setProperty(ServerConfiguration.ENGINE_VERSION, version);
    }

    return false;
}

From source file:com.norconex.importer.handler.transformer.impl.ReplaceTransformerTest.java

@Test
public void testWriteRead() throws IOException {
    ReplaceTransformer t = new ReplaceTransformer();
    Reader reader = new InputStreamReader(IOUtils.toInputStream(xml));
    t.loadFromXML(reader);//w w  w . ja v  a 2s  .  co m
    reader.close();
    System.out.println("Writing/Reading this: " + t);
    ConfigurationUtil.assertWriteRead(t);
}

From source file:IOUtils.java

/**
 * Unconditionally close an <code>Reader</code>.
 * <p>/*  www . j a  v a 2  s.  com*/
 * Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 *
 * @param input  the Reader to close, may be null or already closed
 */
public static void closeQuietly(Reader input) {
    try {
        if (input != null) {
            input.close();
        }
    } catch (IOException ioe) {
        // ignore
    }
}

From source file:com.norconex.importer.handler.transformer.impl.ReduceConsecutivesTransformerTest.java

@Test
public void testWriteRead() throws IOException {
    ReduceConsecutivesTransformer t = new ReduceConsecutivesTransformer();
    Reader reader = new InputStreamReader(IOUtils.toInputStream(xml));
    t.loadFromXML(reader);/*from ww  w  .j a  v  a  2 s .c o  m*/
    reader.close();
    System.out.println("Writing/Reading this: " + t);
    ConfigurationUtil.assertWriteRead(t);
}

From source file:com.celements.web.plugin.cmd.PlainTextCommand.java

public String convertToPlainText(String htmlContent) {
    try {//w  w  w .  j  a  v a2s .c o m
        Reader in = new StringReader(htmlContent);
        Html2Text parser = new Html2Text();
        parser.parse(in);
        in.close();
        return parser.getText();
    } catch (IOException ioExp) {
        LOGGER.error("Fail to convertToPlainText: ", ioExp);
    }
    return "";
}