输出:

使用:
 *  <pre>
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
* </pre>

 
public final class StdOut {

    // force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8"; // assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US; // send output here
private static PrintWriter out; // this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
} // don't instantiate
private StdOut() { } /**
* Closes standard output.
* @deprecated Calling close() permanently disables standard output;
* subsequent calls to StdOut.println() or System.out.println()
* will no longer produce output on standard output.
*/
@Deprecated
public static void close() {
out.close();
} /**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
} /**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
} /**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
} /**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
} /**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
} /**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
} /**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
} /**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
} /**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
} /**
* Prints a byte to standard output and then terminates the line.
* <p>
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
} /**
* Flushes standard output.
*/
public static void print() {
out.flush();
} /**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
} /**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
} /**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
} /**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
} /**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
} /**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
} /**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
} /**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
} /**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
} /**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
} /**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the <a href = "http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax">format string</a>
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
} /**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) { // write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
} }

输入:

方法摘要:

  • * <ul>
  • * <li> {@link #isEmpty()}
  • * <li> {@link #readInt()}
  • * <li> {@link #readDouble()}
  • * <li> {@link #readString()}
  • * <li> {@link #readShort()}
  • * <li> {@link #readLong()}
  • * <li> {@link #readFloat()}
  • * <li> {@link #readByte()}
  • * <li> {@link #readBoolean()}
  • <ul>
  • *  <li> {@link #readAllDoubles()}
  •  *  <li> {@link #readAllInts()}
  •  *  <li> {@link #readAllLongs()}
  •  *  <li> {@link #readAllStrings()}
  •  *  <li> {@link #readAllLines()}
  •  *  <li> {@link #readAll()}
  • *  </ul>

    * </ul>

 

public final class StdIn {

    /*** begin: section (1 of 2) of code duplicated from In to StdIn. */

    // assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8"; // assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US; // the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+"); // makes whitespace significant
private static final Pattern EMPTY_PATTERN = Pattern.compile(""); // used to read the entire input
private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A"); /*** end: section (1 of 2) of code duplicated from In to StdIn. */ private static Scanner scanner; // it doesn't make sense to instantiate this class
private StdIn() { } //// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static" /**
* Returns true if standard input is empty (except possibly for whitespace).
* Use this method to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return {@code true} if standard input is empty (except possibly
* for whitespace); {@code false} otherwise
*/
public static boolean isEmpty() {
return !scanner.hasNext();
} /**
* Returns true if standard input has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return {@code true} if standard input has more input (including whitespace);
* {@code false} otherwise
*/
public static boolean hasNextLine() {
return scanner.hasNextLine();
} /**
* Returns true if standard input has more input (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return {@code true} if standard input has more input (including whitespace);
* {@code false} otherwise
*/
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
} /**
* Reads and returns the next line, excluding the line separator if present.
*
* @return the next line, excluding the line separator if present;
* {@code null} if no such line
*/
public static String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
} /**
* Reads and returns the next character.
*
* @return the next {@code char}
* @throws NoSuchElementException if standard input is empty
*/
public static char readChar() {
try {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'char' value from standard input, "
+ "but no more tokens are available");
}
} /**
* Reads and returns the remainder of the input, as a string.
*
* @return the remainder of the input, as a string
* @throws NoSuchElementException if standard input is empty
*/
public static String readAll() {
if (!scanner.hasNextLine())
return ""; String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
} /**
* Reads the next token and returns the {@code String}.
*
* @return the next {@code String}
* @throws NoSuchElementException if standard input is empty
*/
public static String readString() {
try {
return scanner.next();
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'String' value from standard input, "
+ "but no more tokens are available");
}
} /**
* Reads the next token from standard input, parses it as an integer, and returns the integer.
*
* @return the next integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as an {@code int}
*/
public static int readInt() {
try {
return scanner.nextInt();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read an 'int' value from standard input, "
+ "but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attemps to read an 'int' value from standard input, "
+ "but no more tokens are available");
} } /**
* Reads the next token from standard input, parses it as a double, and returns the double.
*
* @return the next double on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code double}
*/
public static double readDouble() {
try {
return scanner.nextDouble();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'double' value from standard input, "
+ "but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'double' value from standard input, "
+ "but no more tokens are available");
}
} /**
* Reads the next token from standard input, parses it as a float, and returns the float.
*
* @return the next float on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code float}
*/
public static float readFloat() {
try {
return scanner.nextFloat();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'float' value from standard input, "
+ "but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'float' value from standard input, "
+ "but there no more tokens are available");
}
} /**
* Reads the next token from standard input, parses it as a long integer, and returns the long integer.
*
* @return the next long integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code long}
*/
public static long readLong() {
try {
return scanner.nextLong();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'long' value from standard input, "
+ "but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'long' value from standard input, "
+ "but no more tokens are available");
}
} /**
* Reads the next token from standard input, parses it as a short integer, and returns the short integer.
*
* @return the next short integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code short}
*/
public static short readShort() {
try {
return scanner.nextShort();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'short' value from standard input, "
+ "but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'short' value from standard input, "
+ "but no more tokens are available");
}
} /**
* Reads the next token from standard input, parses it as a byte, and returns the byte.
*
* @return the next byte on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code byte}
*/
public static byte readByte() {
try {
return scanner.nextByte();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'byte' value from standard input, "
+ "but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'byte' value from standard input, "
+ "but no more tokens are available");
}
} /**
* Reads the next token from standard input, parses it as a boolean,
* and returns the boolean.
*
* @return the next boolean on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}:
* {@code true} or {@code 1} for true, and {@code false} or {@code 0} for false,
* ignoring case
*/
public static boolean readBoolean() {
try {
String token = readString();
if ("true".equalsIgnoreCase(token)) return true;
if ("false".equalsIgnoreCase(token)) return false;
if ("1".equals(token)) return true;
if ("0".equals(token)) return false;
throw new InputMismatchException("attempts to read a 'boolean' value from standard input, "
+ "but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'boolean' value from standard input, "
+ "but no more tokens are available");
} } /**
* Reads all remaining tokens from standard input and returns them as an array of strings.
*
* @return all remaining tokens on standard input, as an array of strings
*/
public static String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// because trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens; // don't include first token if it is leading whitespace
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length - 1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
} /**
* Reads all remaining lines from standard input and returns them as an array of strings.
* @return all remaining lines on standard input, as an array of strings
*/
public static String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[lines.size()]);
} /**
* Reads all remaining tokens from standard input, parses them as integers, and returns
* them as an array of integers.
* @return all remaining integers on standard input, as an array
* @throws InputMismatchException if any token cannot be parsed as an {@code int}
*/
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
} /**
* Reads all remaining tokens from standard input, parses them as longs, and returns
* them as an array of longs.
* @return all remaining longs on standard input, as an array
* @throws InputMismatchException if any token cannot be parsed as a {@code long}
*/
public static long[] readAllLongs() {
String[] fields = readAllStrings();
long[] vals = new long[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Long.parseLong(fields[i]);
return vals;
} /**
* Reads all remaining tokens from standard input, parses them as doubles, and returns
* them as an array of doubles.
* @return all remaining doubles on standard input, as an array
* @throws InputMismatchException if any token cannot be parsed as a {@code double}
*/
public static double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
} //// end: section (2 of 2) of code duplicated from In to StdIn // do this once when StdIn is initialized
static {
resync();
} /**
* If StdIn changes, use this to reinitialize the scanner.
*/
private static void resync() {
setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME));
} private static void setScanner(Scanner scanner) {
StdIn.scanner = scanner;
StdIn.scanner.useLocale(LOCALE);
} /**
* Reads all remaining tokens, parses them as integers, and returns
* them as an array of integers.
* @return all remaining integers, as an array
* @throws InputMismatchException if any token cannot be parsed as an {@code int}
* @deprecated Replaced by {@link #readAllInts()}.
*/
@Deprecated
public static int[] readInts() {
return readAllInts();
} /**
* Reads all remaining tokens, parses them as doubles, and returns
* them as an array of doubles.
* @return all remaining doubles, as an array
* @throws InputMismatchException if any token cannot be parsed as a {@code double}
* @deprecated Replaced by {@link #readAllDoubles()}.
*/
@Deprecated
public static double[] readDoubles() {
return readAllDoubles();
} /**
* Reads all remaining tokens and returns them as an array of strings.
* @return all remaining tokens, as an array of strings
* @deprecated Replaced by {@link #readAllStrings()}.
*/
@Deprecated
public static String[] readStrings() {
return readAllStrings();
} /**
* Interactive test of basic functionality.
*
* @param args the command-line arguments
*/
public static void main(String[] args) { StdOut.print("Type a string: ");
String s = StdIn.readString();
StdOut.println("Your string was: " + s);
StdOut.println(); StdOut.print("Type an int: ");
int a = StdIn.readInt();
StdOut.println("Your int was: " + a);
StdOut.println(); StdOut.print("Type a boolean: ");
boolean b = StdIn.readBoolean();
StdOut.println("Your boolean was: " + b);
StdOut.println(); StdOut.print("Type a double: ");
double c = StdIn.readDouble();
StdOut.println("Your double was: " + c);
StdOut.println();
} }

Java 标准IO高可用类的更多相关文章

  1. Java的IO流各个类的使用原则

    参考:http://blog.csdn.net/ilibaba/article/details/3955799 Java IO 的一般使用原则(花多眼乱,其实每个类都有专门的作用): 这里有详细介绍: ...

  2. [Java复习] 分布式高可用-Hystrix

    什么是Hystrix? Hystrix 可以让我们在分布式系统中对服务间的调用进行控制,加入一些调用延迟或者依赖故障的容错机制. Hystrix 的设计原则 对依赖服务调用时出现的调用延迟和调用失败进 ...

  3. Java 标准 IO 流编程一览笔录( 下 )

    8.回推流:PushbackInputStream与PushbackReader PushbackInputStream/PushbackReader 用于解析InputStream/Reader内的 ...

  4. java之io之File类的list()方法过滤目录的使用

    java的io的知识中,File类必须掌握.File类是对文件或者文件夹的封装.它本身并不能对所封装的文件进行读写,它封装的只是文件或文件夹的周边知识,比如 大小啦,创建日期啦,路径啦等等. 如果Fi ...

  5. Java 标准 IO 流编程一览笔录( 上 )

    Java标准I/O知识体系图: 1.I/O是什么? I/O 是Input/Output(输入.输出)的简称,输入流可以理解为向内存输入,输出流是从内存输出. 2.流 流是一个连续的数据流,可以从流中读 ...

  6. Java的IO操作---File类

    目标 1)掌握File类作用 2)可以使用file类中方法对文件进行读写操作. File类 唯一与文件有关的类.使用file类可进行创建或删除操作,要想使用File类,首先观察File类的构造方法. ...

  7. Java基础---IO(二)--File类、Properties类、打印流、序列流(合并流)

    第一讲     File类 一.概述 1.File类:文件和目录路径名的抽象表现形式 2.特点: 1)用来将文件或文件夹封装成对象 2)方便于对文件与文件夹的属性信息进行操作 3)File类的实例是不 ...

  8. java之io之file类的常用操作

    java io 中,file类是必须掌握的.它的常用api用法见实例. package com.westward.io; import java.io.File; import java.io.IOE ...

  9. Java:IO流其他类(字节数组流、字符数组流、数据流、打印流、Properities、对象流、管道流、随机访问、序列流、字符串读写流)

    一.字节数组流: 类 ByteArrayInputStream:在构造函数的时候,需要接受数据源,而且数据源是一个字节数组. 包含一个内部缓冲区,该缓冲区包含从流中读取的字节.内部计数器跟踪 read ...

随机推荐

  1. numpy.percentile

    http://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html numpy.percentile(a, q, axi ...

  2. 修改Windows帐户密码,导致Sql Server 2000无法启动

    修改Windows帐户密码,导致Sql Server 2000无法启动. --现象以管理员或同等权限用户登录 Windows XP,建立 Sql Server 2000 数据库.之后,在修改此 Win ...

  3. DAY11-MYSQL之ORM框架SQLAlchemy

    一 介绍 SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取 ...

  4. 运行程序显示:Could not find version 8.3 of the MCR.

  5. python爬虫(6)--Requests库的用法

    1.安装 利用pip来安装reques库,进入pip的下载位置,打开cmd,默认地址为 C:\Python27\Scripts 可以看到文件中有pip.exe,直接在上面输入cmd回车,进入命令行界面 ...

  6. JAVA反射机制学习随笔

    JAVA反射机制是用于在运行时动态的获取类的信息或者方法,属性,也可以用来动态的生成类,由于所有类都是CLASS的子类,我们可以用一个CLASS类的实例来实例化各种类 例如: Class<?&g ...

  7. day17-jdbc 4.DriverManager详解

    我们找的不是J2EE的API,因为JDBC不在web程序用也可以,纯java也能玩.所以jdbc的api在java se那里,或者说是在jdk那里. DriverManger它底层有一个集合是一个Ve ...

  8. Vbs 脚本编程简明教程之一

    —为什么要使用 Vbs ? 在 Windows 中,学习计算机操作也许很简单,但是很多计算机工作是重复性劳动,例如你每周也许需要对一些计算机文件进行复制.粘贴.改名.删除,也许你每天启动 计算机第一件 ...

  9. 36-图像有用区(dfs, bfs)

    http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=92 图像有用区域 时间限制:3000 ms  |  内存限制:65535 KB 难度:4   ...

  10. Python 黑客 --- 002 入门级 ZIP压缩文件口令暴力破解机

    Python 黑客 入门级实战:ZIP压缩文件口令暴力破解机 使用的系统:Ubuntu 14.04 LTS Python语言版本:Python 2.7.10 V 编写zip 压缩文件口令破解器需要使用 ...