Java/File Input Output/BufferedReader
Содержание
- 1 A simple FilterReader that strips HTML tags out of a stream of characters
- 2 A standalone program that reads a list of classes and builds a database of packages, classes, and class fields and methods
- 3 Call the static method PressAnykey to keep to "DOS" window open.
- 4 Create BufferedReader from FileReader and Read / display lines from file
- 5 Create BufferedReader from InputStreamReader and System.in, read console input
- 6 Create BufferedReader from StringReader
- 7 Create BufferedReader from System.in
- 8 Create BufferedReader from URL
- 9 Create BufferedReader out of FileReader
- 10 List of lines in a file with BufferedReader
- 11 Read a text file
- 12 Read content of a file
- 13 Read each line in a comma separated file into an array
- 14 Read from a file using a BufferedReader
- 15 Reading Text from a File
- 16 Read lines of text from a file with the BufferedReader class
- 17 ReadLines: read file to list of strings
- 18 Tab filter: Convert tab to space characters
- 19 Use BufferedReader to Read and process lines from console
- 20 Use BufferedReader to read line by line
- 21 Using BufferedReader to read input number from user
A simple FilterReader that strips HTML tags out of a stream of characters
<source lang="java">
/*
* Copyright (c) 2004 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 3nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose, * including teaching and use in open-source projects. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book, * please visit http://www.davidflanagan.ru/javaexamples3. */
import java.io.BufferedReader; import java.io.FileReader; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; /**
* A simple FilterReader that strips HTML tags (or anything between pairs of * angle brackets) out of a stream of characters. */
public class RemoveHTMLReader extends FilterReader {
/** A trivial constructor. Just initialize our superclass */ public RemoveHTMLReader(Reader in) { super(in); } boolean intag = false; // Used to remember whether we are "inside" a tag /** * This is the implementation of the no-op read() method of FilterReader. It * calls in.read() to get a buffer full of characters, then strips out the * HTML tags. (in is a protected field of the superclass). */ public int read(char[] buf, int from, int len) throws IOException { int numchars = 0; // how many characters have been read // Loop, because we might read a bunch of characters, then strip them // all out, leaving us with zero characters to return. while (numchars == 0) { numchars = in.read(buf, from, len); // Read characters if (numchars == -1) return -1; // Check for EOF and handle it. // Loop through the characters we read, stripping out HTML tags. // Characters not in tags are copied over previous tags int last = from; // Index of last non-HTML char for (int i = from; i < from + numchars; i++) { if (!intag) { // If not in an HTML tag if (buf[i] == "<") intag = true; // check for tag start else buf[last++] = buf[i]; // and copy the character } else if (buf[i] == ">") intag = false; // check for end of tag } numchars = last - from; // Figure out how many characters remain } // And if it is more than zero characters return numchars; // Then return that number. } /** * This is another no-op read() method we have to implement. We implement it * in terms of the method above. Our superclass implements the remaining * read() methods in terms of these two. */ public int read() throws IOException { char[] buf = new char[1]; int result = read(buf, 0, 1); if (result == -1) return -1; else return (int) buf[0]; } /** The test program: read a text file, strip HTML, print to console */ public static void main(String[] args) { try { if (args.length != 1) throw new IllegalArgumentException("Wrong number of args"); // Create a stream to read from the file and strip tags from it BufferedReader in = new BufferedReader(new RemoveHTMLReader(new FileReader(args[0]))); // Read line by line, printing lines to the console String line; while ((line = in.readLine()) != null) System.out.println(line); in.close(); // Close the stream. } catch (Exception e) { System.err.println(e); System.err.println("Usage: java RemoveHTMLReader$Test" + " <filename>"); } }
}
</source>
A standalone program that reads a list of classes and builds a database of packages, classes, and class fields and methods
<source lang="java">
/*
* Copyright (c) 2004 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 3nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose, * including teaching and use in open-source projects. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book, * please visit http://www.davidflanagan.ru/javaexamples3. */
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Properties; /**
* This class is a standalone program that reads a list of classes and builds a * database of packages, classes, and class fields and methods. */
public class MakeAPIDB {
public static void main(String args[]) { Connection c = null; // The connection to the database try { // Read the classes to index from a file specified by args[0] ArrayList classnames = new ArrayList(); BufferedReader in = new BufferedReader(new FileReader(args[0])); String name; while ((name = in.readLine()) != null) classnames.add(name); // Now determine the values needed to set up the database // connection The program attempts to read a property file named // "APIDB.props", or optionally specified by args[1]. This // property file (if any) may contain "driver", "database", "user", // and "password" properties that specify the necessary values for // connecting to the db. If the properties file does not exist, or // does not contain the named properties, defaults will be used. Properties p = new Properties(); // Empty properties try { p.load(new FileInputStream(args[1])); // Try to load properties } catch (Exception e1) { try { p.load(new FileInputStream("APIDB.props")); } catch (Exception e2) { } } // Read values from Properties file String driver = p.getProperty("driver"); String database = p.getProperty("database"); String user = p.getProperty("user", ""); String password = p.getProperty("password", ""); // The driver and database properties are mandatory if (driver == null) throw new IllegalArgumentException("No driver specified!"); if (database == null) throw new IllegalArgumentException("No database specified!"); // Load the driver. It registers itself with DriverManager. Class.forName(driver); // And set up a connection to the specified database c = DriverManager.getConnection(database, user, password); // Create three new tables for our data // The package table contains a package id and a package name. // The class table contains a class id, a package id, and a name. // The member table contains a class id, a member name, and an bit // that indicates whether the class member is a field or a method. Statement s = c.createStatement(); s.executeUpdate("CREATE TABLE package " + "(id INT, name VARCHAR(80))"); s.executeUpdate("CREATE TABLE class " + "(id INT, packageId INT, name VARCHAR(48))"); s.executeUpdate("CREATE TABLE member " + "(classId INT, name VARCHAR(48), isField BIT)"); // Prepare some statements that will be used to insert records into // these three tables. insertpackage = c.prepareStatement("INSERT INTO package VALUES(?,?)"); insertclass = c.prepareStatement("INSERT INTO class VALUES(?,?,?)"); insertmember = c.prepareStatement("INSERT INTO member VALUES(?,?,?)"); // Now loop through the list of classes and use reflection // to store them all in the tables int numclasses = classnames.size(); for (int i = 0; i < numclasses; i++) { try { storeClass((String) classnames.get(i)); } catch (ClassNotFoundException e) { System.out.println("WARNING: class not found: " + classnames.get(i) + "; SKIPPING"); } } } catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Usage: java MakeAPIDB " + "<classlistfile> <propfile>"); } // When we"re done, close the connection to the database finally { try { c.close(); } catch (Exception e) { } } } /** * This hash table records the mapping between package names and package id. * This is the only one we need to store temporarily. The others are stored in * the db and don"t have to be looked up by this program */ static Map package_to_id = new HashMap(); // Counters for the package and class identifier columns static int packageId = 0, classId = 0; // Some prepared SQL statements for use in inserting // new values into the tables. Initialized in main() above. static PreparedStatement insertpackage, insertclass, insertmember; /** * Given a fully-qualified classname, this method stores the package name in * the package table (if it is not already there), stores the class name in * the class table, and then uses the Java Reflection API to look up all * methods and fields of the class, and stores those in the member table. */ public static void storeClass(String name) throws SQLException, ClassNotFoundException { String packagename, classname; // Dynamically load the class. Class c = Class.forName(name); // Display output so the user knows that the program is progressing System.out.println("Storing data for: " + name); // Figure out the packagename and the classname int pos = name.lastIndexOf("."); if (pos == -1) { packagename = ""; classname = name; } else { packagename = name.substring(0, pos); classname = name.substring(pos + 1); } // Figure out what the package id is. If there is one, then this // package has already been stored in the database. Otherwise, assign // an id, and store it and the packagename in the db. Integer pid; pid = (Integer) package_to_id.get(packagename); // Check hashtable if (pid == null) { pid = new Integer(++packageId); // Assign an id package_to_id.put(packagename, pid); // Remember it insertpackage.setInt(1, packageId); // Set statement args insertpackage.setString(2, packagename); insertpackage.executeUpdate(); // Insert into package db } // Now, store the classname in the class table of the database. // This record includes the package id, so that the class is linked to // the package that contains it. To store the class, we set arguments // to the PreparedStatement, then execute that statement insertclass.setInt(1, ++classId); // Set class identifier insertclass.setInt(2, pid.intValue()); // Set package identifier insertclass.setString(3, classname); // Set class name insertclass.executeUpdate(); // Insert the class record // Now, get a list of all non-private methods of the class, and // insert those into the "members" table of the database. Each // record includes the class id of the containing class, and also // a value that indicates that these are methods, not fields. Method[] methods = c.getDeclaredMethods(); // Get a list of methods for (int i = 0; i < methods.length; i++) { // For all non-private if (Modifier.isPrivate(methods[i].getModifiers())) continue; insertmember.setInt(1, classId); // Set the class id insertmember.setString(2, methods[i].getName()); // Set method name insertmember.setBoolean(3, false); // It is not a field insertmember.executeUpdate(); // Insert into db } // Do the same thing for the non-private fields of the class Field[] fields = c.getDeclaredFields(); // Get a list of fields for (int i = 0; i < fields.length; i++) { // For each non-private if (Modifier.isPrivate(fields[i].getModifiers())) continue; insertmember.setInt(1, classId); // Set the class id insertmember.setString(2, fields[i].getName()); // Set field name insertmember.setBoolean(3, true); // It is a field insertmember.executeUpdate(); // Insert the record } }
}
</source>
Call the static method PressAnykey to keep to "DOS" window open.
<source lang="java">
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main{
public static void main(String[] args) { PressAnyKey(); } public static void PressAnyKey() { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Press any key..."); try { input.readLine(); } catch (Exception e) { e.printStackTrace(); } }
}
</source>
Create BufferedReader from FileReader and Read / display lines from file
<source lang="java">
import java.io.BufferedReader; import java.io.FileReader; class BufferedReaderDemo {
public static void main(String args[]) throws Exception { FileReader fr = new FileReader(args[0]); // Create a buffered reader BufferedReader br = new BufferedReader(fr); // Read and display lines from file String s; while ((s = br.readLine()) != null) System.out.println(s); fr.close(); }
}
</source>
Create BufferedReader from InputStreamReader and System.in, read console input
<source lang="java">
import java.io.BufferedReader; import java.io.InputStreamReader; class Main {
public static void main(String args[]) throws Exception { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); while (true) { System.out.print("Radius? "); String str = br.readLine(); double radius; try { radius = Double.valueOf(str).doubleValue(); } catch (NumberFormatException nfe) { System.out.println("Incorrect format!"); continue; } if (radius <= 0) { System.out.println("Radius must be positive!"); continue; } System.out.println("radius " + radius); return; } }
}
</source>
Create BufferedReader from StringReader
<source lang="java">
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringReader; public class Main {
public static void main(String[] args) throws Exception { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.println(stdin.readLine()); BufferedReader in = new BufferedReader(new FileReader("Main.java")); String s, s2 = new String(); while ((s = in.readLine()) != null) s2 += s + "\n"; in.close(); StringReader in1 = new StringReader(s2); int c; while ((c = in1.read()) != -1) System.out.print((char) c); BufferedReader in2 = new BufferedReader(new StringReader(s2)); PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter( "IODemo.out"))); int lineCount = 1; while ((s = in2.readLine()) != null) out1.println(lineCount++ + ": " + s); out1.close(); }
}
</source>
Create BufferedReader from System.in
<source lang="java">
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Main {
public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String strLine = in.readLine(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); out.write(strLine, 0, strLine.length()); out.flush(); in.close(); out.close(); }
}
</source>
Create BufferedReader from URL
<source lang="java">
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class Main {
public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:1776"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); }
}
</source>
Create BufferedReader out of FileReader
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class CopyLines {
public static void main(String[] args) throws IOException { BufferedReader inputStream = null; PrintWriter outputStream = null; try { inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new PrintWriter(new FileWriter("characteroutput.txt")); String l; while ((l = inputStream.readLine()) != null) { outputStream.println(l); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }
}
</source>
List of lines in a file with BufferedReader
<source lang="java">
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; public class FileList {
public static void main(String[] args) { final int assumedLineLength = 50; File file = new File(args[0]); List<String> fileList = new ArrayList<String>((int) (file.length() / assumedLineLength) * 2); BufferedReader reader = null; int lineCount = 0; try { reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { fileList.add(line); lineCount++; } } catch (IOException e) { System.err.format("Could not read %s: %s%n", file, e); System.exit(1); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } int repeats = Integer.parseInt(args[1]); Random random = new Random(); for (int i = 0; i < repeats; i++) { System.out.format("%d: %s%n", i, fileList.get(random.nextInt(lineCount - 1))); } }
}
</source>
Read a text file
<source lang="java">
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class Main {
public static void main(String[] args) throws Exception { File file = new File("test.txt"); StringBuffer contents = new StringBuffer(); BufferedReader reader = null; reader = new BufferedReader(new FileReader(file)); String text = null; // repeat until all lines is read while ((text = reader.readLine()) != null) { contents.append(text).append(System.getProperty("line.separator")); } reader.close(); System.out.println(contents.toString()); }
}
</source>
Read content of a file
<source lang="java">
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class Main {
public static void main(String[] argv) { readTextFile(new File("c:\\a.txt")); } public static String readTextFile(File filename) { try { BufferedReader br = new BufferedReader(new FileReader(filename)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line + "\n"); line = br.readLine(); } br.close(); return sb.toString(); } catch (Exception e) { e.printStackTrace(); System.err.println(filename); System.err.println(e); return ""; } }
}
</source>
Read each line in a comma separated file into an array
<source lang="java">
import java.io.BufferedReader; import java.io.FileReader; public class Main {
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("thefile.csv")); String line = null; while ((line = br.readLine()) != null) { String[] values = line.split(","); for (String str : values) { System.out.println(str); } } br.close(); }
}
</source>
Read from a file using a BufferedReader
<source lang="java">
import java.io.BufferedReader; import java.io.FileReader; public class Main {
public static void main(String[] args) throws Exception { BufferedReader bufferedReader = new BufferedReader(new FileReader("yourFile.txt")); String line = null; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); }
}
</source>
Reading Text from a File
<source lang="java">
import java.io.BufferedReader; import java.io.FileReader; public class Main {
public static void main(String[] argv) throws Exception { BufferedReader in = new BufferedReader(new FileReader("infilename")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); }
}
</source>
Read lines of text from a file with the BufferedReader class
<source lang="java">
import java.io.BufferedReader; import java.io.FileReader; public class Main {
public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new FileReader("filename.txt")); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); }
}
</source>
ReadLines: read file to list of strings
<source lang="java">
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class Utils {
public static List<String> readLines(File file) throws Exception { if (!file.exists()) { return new ArrayList<String>(); } BufferedReader reader = new BufferedReader(new FileReader(file)); List<String> results = new ArrayList<String>(); String line = reader.readLine(); while (line != null) { results.add(line); line = reader.readLine(); } return results; }
}
</source>
Tab filter: Convert tab to space characters
<source lang="java">
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; class TabFilter {
public static void main(String args[]) throws Exception { FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(args[1]); BufferedWriter bw = new BufferedWriter(fw); // Convert tab to space characters String s; while ((s = br.readLine()) != null) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == "\t") c = " "; bw.write(c); } } bw.flush(); fr.close(); fw.close(); }
}
</source>
Use BufferedReader to Read and process lines from console
<source lang="java">
import java.io.BufferedReader; import java.io.InputStreamReader; class ReverseConsoleInput {
public static void main(String args[]) throws Exception { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); // Read and process lines from console String s; while ((s = br.readLine()) != null) { StringBuffer sb = new StringBuffer(s); sb.reverse(); System.out.println(sb); } isr.close(); }
}
</source>
Use BufferedReader to read line by line
<source lang="java">
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class Main {
public static void main(String args[]) throws Exception { File file = new File("."); if (file.isDirectory()) { String[] files = file.list(); for (int i = 0; i < files.length; i++) System.out.println(files[i]); } else { FileReader fr = new FileReader(file); BufferedReader in = new BufferedReader(fr); String line; while ((line = in.readLine()) != null) System.out.println(line); } }
}
</source>
Using BufferedReader to read input number from user
<source lang="java">
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main {
public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String input = reader.readLine(); double number = Double.parseDouble(input); System.out.println(input + ":" + Math.sqrt(number)); reader.close(); }
}
</source>