get BufferedReader from file URL - Java Network

Java examples for Network:URL Download

Description

get BufferedReader from file URL

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class Main {
    public static void main(String[] argv) throws Exception {
        String fileUrl = "java2s.com";
        String encoding = "java2s.com";
        System.out.println(getReader(fileUrl, encoding));
    }/*from  w w w  . j  a  v  a 2s.  com*/

    public static BufferedReader getReader(String fileUrl, String encoding)
            throws IOException {
        InputStreamReader reader;
        try {
            if (encoding == null) {
                reader = new FileReader(fileUrl);
            } else {
                reader = new InputStreamReader(
                        new FileInputStream(fileUrl), encoding);
            }
        } catch (FileNotFoundException e) {
            // try a real URL instead
            URL url = new URL(fileUrl);
            if (encoding == null) {
                reader = new InputStreamReader(url.openStream());
            } else {
                reader = new InputStreamReader(url.openStream(), encoding);
            }
        }
        return new BufferedReader(reader);
    }
}

Related Tutorials