简化java输入输出
这是一个简化java中输入输出的包。平时自己只是用到其中的少数的几个,
把它贴出来,希望能给学习java的人带来方便。




Console.java

package tio;
import java.io.*;

/**
* The class <code>Console</code> is a convenience class.
* It contains a static variable <code>in</code> that is
* initialized to refer to a ReadInput object, reading
* from the standard input stream System.in.
* It also contains a static variable <code>out</code>
* that is initialized to refer to a FormattedWriter,
* writing to the output stream System.out.
*/

public class Console {
public final static ReadInput in =
new ReadInput(new InputStreamReader(System.in));
public final static FormattedWriter out =
new FormattedWriter(System.out);
}



<------------------------------------------------------------------->




ReadException.java

package tio;


import java.io.*;

/**
* The class <code>ReadException</code> is used to convert
* java.io.IOExceptions into a subtype of
* RuntimeException. By doing this, users of ReadInput
* methods do not need to use throws declarations,
* simplifying beginning programs. Subtypes of
* RuntimeException do not need to be declared using
* a throws clause.
*
* @author C. E. McDowell
* @version 1.1, Released for Java By Dissection
*
*/

public class ReadException extends RuntimeException {

/**
* Constructs a ReadException object with no
* specific message.
*/

public ReadException() {
super();
}

/**
* Constructs a ReadException object with the
* specified message.
*
* @param message the error message
*/

public ReadException(String message) {
super(message);
}
}






<-------------------------------------------------------------------->




PrintFileWriter.java




package tio;

import java.io.*;

/**
* The class <code>PrintFileWriter</code> is a
* convenience class. It adds one constructor to its
* parent class, PrintWriter. This new constructor
* takes the name of a file.
* <p>
* <code>new PrintFileWriter(fileName)</code> is the
* same as <code>
* new PrintWriter(new FileWriter(fileName))
* </code>.
*/

public class PrintFileWriter extends PrintWriter {
public PrintFileWriter(String filename)
throws IOException
{
super(new FileWriter(filename));
}
}




<-------------------------------------------------------------------->




ReadInput.java




package tio;

import java.io.*;

/**
* The class <code>ReadInput</code> contains methods that
* allow for simple input of numbers, strings and
* characters from a text stream.
*
* @author C. E. McDowell
* @version 1.1, release for Java By Dissection
*/

public class ReadInput {

/**
* Constructs a ReadInput object for reading from any
* Reader object.
*
* @param input the Reader text stream to read from.
*/

public ReadInput(Reader input) {
// can look ahead over 1024 white space characters
// when checking for the end of file mark
this.input = new PushbackReader(input, 1024);
}

/**
* Constructs a ReadInput object for reading from a
* file.
*
* @param filename the name of the file from which
* to read.
* @exception FileNotFoundException if the file can't
* be opened.
*/

public ReadInput(String filename) {
try {
FileReader fin = new FileReader(filename);
this.input = new PushbackReader(fin, 1024);
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Constructs a ReadInput object for reading from any
* InputStream.
*
* @param input the InputStream to read from.
*/

public ReadInput(InputStream input) {
this(new InputStreamReader(input));
}

/**
* Check to see if there are any non-white space
* characters left in the input. If used to terminate
* reading with readLine(), any trailing blank lines
* will be ignored. To read trailing blank lines, do
* not use hasMoreElements() and instead read with
* readLine() until an EOFException is thrown.
*
* @return true if the input contains more non-white
* space characters and false otherwise.
*/

public boolean hasMoreElements() {
try {
if (atEof)
return false;
else if (whiteSpaceBuffered)
return true;
//something followed the white space
// look ahead to see if any non-white remain
int nextChar = input.read();
if (Character.isWhitespace((char)nextChar)) {
// save white space in case readLine() comes next
whiteSpaceBuffered = true;
buffer[0] = (char)nextChar;
for (bufferCount = 1; bufferCount < 1024;
++bufferCount)
{
nextChar = input.read();
if (nextChar == -1) {
atEof = true;
break;
}
else if
(!Character.isWhitespace((char)nextChar))
{
input.unread(nextChar);
break;
}
buffer[bufferCount] = (char)nextChar;
}
//end for
}
else if (nextChar == -1) {
atEof = true;
input.unread(nextChar);
}
else
input.unread(nextChar);
return !atEof;
}
catch(java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Read the next character. White space is not skipped.
* readChar() cannot be used to reread input characters
* that resulted in a NumberFormatException trying
* to read a number. readLine() will return the
* characters of a failed number read.
*
* @return the int value of the next character.
*/

public int readChar() {
try {
int result;
// tokenRead will be true if a token was read
// but couldn't be parsed. readChar() cannot
// be used to reread such a token, discard it.
tokenRead = false;
if (whiteSpaceBuffered) {
input.unread(buffer, 0, bufferCount);
whiteSpaceBuffered = false;
}
result = input.read();
if (result == -1)
atEof = true;
return result;
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Attempt to interpret the next white space delimited
* input characters as a double.
*
* @return the double value of the next, white-space
* delimited input string.
* @exception NumberFormatException if the next input
* string does not contain a parsable double.
*/

public double readDouble() {
try {
readToken();
double result = Double.parseDouble(token);
tokenRead = false;
// this token has been used up
return result;
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Attempt to interpret the next white space delimited
* input characters as a float.
*
* @return the float value of the next, white-space
* delimited input string.
* @exception NumberFormatException if the next input
* string does not contain a parsable float.
*/

public float readFloat() {
try {
readToken();
float result = Float.parseFloat(token);
tokenRead = false;
// this token has been used up
return result;
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Attempt to interpret the next white space delimited
* input characters as an int.
*
* @return the int value of the next, white-space
* delimited input string.
* @exception NumberFormatException if the next input
* string does not contain a parsable int.
*/

public int readInt() {
try {
readToken();
int result = Integer.parseInt(token);
tokenRead = false;
// this token has been used up
return result;
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Read the next complete input line up to the newline
* character. The terminating newline character is read
* and discarded. It is not part of the return string.
* If the previous read was an attempt to read a number
* that generated a NumberFormatException, readLine()
* will return the input line including the input
* characters that caused the exception. This can be
* used to try and recover from failure to read numeric
* input.
*
* @return the next input line as a String.
*/

public String readLine() {
try {
if (tokenRead) {
tokenRead = false;
return token + readLine(input);
}
else {
return readLine(input);
}
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Attempt to interpret the next white space delimited
* input characters as a long.
*
* @return the long value of the next, white-space
* delimited input string.
* @exception NumberFormatException if the next input
* string does not contain a parsable long.
*/

public long readLong() {
try {
readToken();
long result = Long.parseLong(token);
tokenRead = false;
// this token has been used up
return result;
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Read the next white space delimited string.
*
* @return the next, white-space delimited input string.
*/

public String readWord() {
try {
readToken();
tokenRead = false;
// this token has been used up
return token;
}
catch (java.io.IOException e) {
throw new ReadException(e.toString());
}
}

/**
* Do the work of reading a line of text.
* White space may have been buffered up from a
* call to hasMoreElements(). If so, unread the
* buffered white space then read one line.
*/

private String readLine(PushbackReader in)
throws IOException
{
StringBuffer result = new StringBuffer(80);
if (whiteSpaceBuffered) {
in.unread(buffer, 0, bufferCount);
whiteSpaceBuffered = false;
}
int nextChar = in.read();
while (nextChar != -1 && nextChar != '\n' &&
nextChar != '\r') {
result.append((char)nextChar);
nextChar = in.read();
}
if (nextChar == -1) {
atEof = true;
in.unread(nextChar);
}
else if (nextChar == '\r') {
nextChar = in.read();
// check for cr/newline
if (nextChar != '\n')
in.unread(nextChar);
}
if (atEof && result.length() == 0)
return null;
else
return result.toString();
}

/**
* Read the next white space delimited string.
* This will then be parsed by the appropriate
* routine to return one of the desired types.
*/

private void readToken() throws IOException {
if (atEof)
throw new EOFException(
"Attempt to read beyond the end of the stream.");
if (!tokenRead) {
//discard any buffered white space
whiteSpaceBuffered = false;
StringBuffer result = new StringBuffer(80);
int nextChar = input.read();
while (Character.isWhitespace((char)nextChar))
nextChar = input.read();
while (nextChar != -1 && nextChar != '\n' &&
nextChar != '\r' &&
!Character.isWhitespace((char)nextChar))
{
result.append((char)nextChar);
nextChar = input.read();
}
token = result.toString();
if (nextChar == -1)
if(token.length() == 0)
throw new EOFException(
"Attempt to read beyond the end of the stream.");
else
atEof = true;
input.unread(nextChar);
tokenRead = true;
}
}

private String token;
private boolean tokenRead = false;
private PushbackReader input;
private boolean atEof = false;
private boolean whiteSpaceBuffered = false;
private char[] buffer = new char[1024];
private int bufferCount;
}



<-------------------------------------------------------------------->




FormattedWriter.java


package tio;

import java.io.*;
import java.text.*;

/**
* The class <code>FormattedWriter</code> contains
* methods that allow for formatted printing.
* It includes support for setting the width of the
* output field, using left or right justification in
* the output field, using an arbitrary fill
* character, and setting the number of digits to the
* right of the decimal point in floating point
* values.
*
* @author C. E. McDowell
* @version 1.2 corrected problem with floats with exponents.
*/

public class FormattedWriter extends PrintWriter {
// constants for specifying justification
public static final int LEFT = 1;
public static final int RIGHT = 2;

/**
* Constructs a FormattedWriter object for an
* OutputStream.
*
* @param os the OutputStream to write to
*/

public FormattedWriter(OutputStream os) {
super(os, true);
// make default auto-flushing
}

/**
* Constructs a FormattedWriter object for a
* FileWriter.
*
* @param writer the FileWriter to write to
*/

public FormattedWriter(FileWriter writer) {
super(writer, true);
}

/**
* Constructs a FormattedWriter object for writing
* to a file.
*
* @param filename the name of the file to write to
*/

public FormattedWriter(String filename)
throws java.io.IOException
{
this(new FileWriter(filename));
}

/**
* Set the output field width. If the value being
* printed is less than the width of the field, then
* the field will be padded with the pad character
* (see setPadChar()). The field can be either left
* or right justified (see setJustify()).
*
* @param width the width of the output field
*/

public void setWidth(int width) {
if (width < 0)
this.width = 0;
else if (width > MAX_WIDTH)
this.width = MAX_WIDTH;
else
this.width = width;
}

/**
* Set the number of digits to be printed to the
* right of the decimal point in floating point
* values.
*
* @param places the number of places to the right
* of the decimal point
*/

public void setDigits(int places) {
decimalPlaces = places;
form.setMaximumFractionDigits(decimalPlaces);
}

/**
* Set the justification to be LEFT or RIGHT.
*
* @param leftOrRight use FormattedWriter.LEFT
* or FormattedWriter.RIGHT
* @exception IllegalArgumentException if not LEFT
* or RIGHT
*/

public void setJustify(int leftOrRight) {
if (leftOrRight != LEFT && leftOrRight != RIGHT)
throw new IllegalArgumentException(
"use FormattedWriter.LEFT or" +
" FormattedWriter.RIGHT");
justify = leftOrRight;
}

/**
* Set the character to be used in padding.
* The default padding character is a blank.
*
* @param pad the character to use in padding
*/

public void setPadChar(char pad) {
if (pad == ' ')
padding = spaces;
else if (pad == '0')
padding = zeros;
else
padding = buildPadding(MAX_WIDTH, pad);
}

/**
* Print a String in a field of the current
* width using the current padding character
* and justification.
*
* @param s the String to print
*/

public void printf(String s) {
if (s.length() >= width)
super.print(s);
else if (justify == LEFT)
super.print(s +
padding.substring(0, width - s.length()));
else
super.print(
padding.substring(0, width - s.length()) + s);
}


/**
* Print a boolean in a field of the current
* width, using the current padding character and justification.
*
* @param value the value to print
*/

public void printf(boolean value) {
printf(String.valueOf(value));
}

/**
* Print a char in a field of the current
* width, using the current padding character and justification.
*
* @param value the value to print
*/

public void printf(char value) {
printf(String.valueOf(value));
}

/**
* Print an array of characters in a field of the current
* width, using the current padding character and justification.
*
* @param value the value to print
*/

public void printf(char[] value) {
printf(String.valueOf(value));
}

/**
* Print an int in a field of the current
* width, using the current padding character and justification.
*
* @param value the value to print
*/

public void printf(int value) {
printf(String.valueOf(value));
}

/**
* Print a long in a field of the current
* width, using the current padding character and justification.
*
* @param value the value to print
*/

public void printf(long value) {
printf(String.valueOf(value));
}

/**
* Print any Object in a field of the current
* width, using the current padding character and justification.
*
* @param value the value to print
*/

public void printf(Object value) {
printf(value.toString());
}

/**
* Print a double in a field of the current
* width, with the current number of digits to the
* right of the decimal point and using the current
* padding character and justification.
*
* @param value the value to print
*/

public void printf(double value) {
printf(trimDigits(String.valueOf(value)));
}

/**
* Print a float in a field of the current
* width, with the current number of digits to the
* right of the decimal point and using the current
* padding character and justification.
*
* @param value the value to print
*/

public void printf(float value) {
printf(trimDigits(String.valueOf(value)));
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(String s) {
printf(s);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(boolean value) {
printf(value);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(char value) {
printf(value);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(char[] value) {
printf(value);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(int value) {
printf(value);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(long value) {
printf(value);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(Object value) {
printf(value);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(double value) {
printf(value);
println();
}

/**
* Same as printf() with a newline added at the end.
*/

public void printfln(float value) {
printf(value);
println();
}

/*
* Trim the number of digits to the right of the
* decimal point if there is one.
*/

private String trimDigits(String value) {
int places;

if (decimalPlaces == -1)
return value;
int pos = value.indexOf(
".");
int exp = value.indexOf(
"E");
if (exp == -1)
places = value.length() - pos - 1;
else
places = exp - pos - 1;
if (places <= decimalPlaces)
return value;
if (exp == -1)
return round(value);
else {
String needsRounding = value.substring(0, exp);
return round(needsRounding) +
value.substring(exp);
}
}

/*
* Round the last digit of s. E.g. 1.2345 would be
* returned as 1.235 and 1.234 would be returned as
* 1.23.
* This is done using a java.text.NumberFormat
* object that had its decimal places set in
* setDigits() above.
*/

private String round(String s) {
// form is a java.text.NumberFormat object
return form.format(Double.parseDouble(s));
}

/*
* Create an array of pad characters used for
* quickly building strings of pad characters
* by a call to substring (see printfln(String s))
*/

private static String buildPadding(int width,
char pad)
{
StringBuffer sbuf = new StringBuffer(width);
for (int i = 0; i < width; ++i)
sbuf.append(pad);
return sbuf.toString();
}

private static int MAX_WIDTH = 40;
private static final String spaces =
buildPadding(MAX_WIDTH, ' ');
private static final String zeros =
buildPadding(MAX_WIDTH, '0');
private String padding = spaces;
private int width = 0;
private int justify = LEFT;

// -1 means use max precision
private int decimalPlaces = -1;
// used in trimming decimal digits
private NumberFormat form =
NumberFormat.getInstance();
}



air_tuyh   2005-04-27 21:28:09 评论:2   阅读:2094   引用:0
@2007-11-29 18:20:30  游客
ftp://ftp.awl.com/cseng/authors/pohl-mcdowell/source%20code/
原文件在这个地方,用了别人的东西该注明出处
@2007-02-27 17:20:25  游客
好东东,正在找它,先用了,谢谢呀。

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2008 powered by YuLog