Java 标准IO高可用类
输出:
使用:
* <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高可用类的更多相关文章
- Java的IO流各个类的使用原则
参考:http://blog.csdn.net/ilibaba/article/details/3955799 Java IO 的一般使用原则(花多眼乱,其实每个类都有专门的作用): 这里有详细介绍: ...
- [Java复习] 分布式高可用-Hystrix
什么是Hystrix? Hystrix 可以让我们在分布式系统中对服务间的调用进行控制,加入一些调用延迟或者依赖故障的容错机制. Hystrix 的设计原则 对依赖服务调用时出现的调用延迟和调用失败进 ...
- Java 标准 IO 流编程一览笔录( 下 )
8.回推流:PushbackInputStream与PushbackReader PushbackInputStream/PushbackReader 用于解析InputStream/Reader内的 ...
- java之io之File类的list()方法过滤目录的使用
java的io的知识中,File类必须掌握.File类是对文件或者文件夹的封装.它本身并不能对所封装的文件进行读写,它封装的只是文件或文件夹的周边知识,比如 大小啦,创建日期啦,路径啦等等. 如果Fi ...
- Java 标准 IO 流编程一览笔录( 上 )
Java标准I/O知识体系图: 1.I/O是什么? I/O 是Input/Output(输入.输出)的简称,输入流可以理解为向内存输入,输出流是从内存输出. 2.流 流是一个连续的数据流,可以从流中读 ...
- Java的IO操作---File类
目标 1)掌握File类作用 2)可以使用file类中方法对文件进行读写操作. File类 唯一与文件有关的类.使用file类可进行创建或删除操作,要想使用File类,首先观察File类的构造方法. ...
- Java基础---IO(二)--File类、Properties类、打印流、序列流(合并流)
第一讲 File类 一.概述 1.File类:文件和目录路径名的抽象表现形式 2.特点: 1)用来将文件或文件夹封装成对象 2)方便于对文件与文件夹的属性信息进行操作 3)File类的实例是不 ...
- java之io之file类的常用操作
java io 中,file类是必须掌握的.它的常用api用法见实例. package com.westward.io; import java.io.File; import java.io.IOE ...
- Java:IO流其他类(字节数组流、字符数组流、数据流、打印流、Properities、对象流、管道流、随机访问、序列流、字符串读写流)
一.字节数组流: 类 ByteArrayInputStream:在构造函数的时候,需要接受数据源,而且数据源是一个字节数组. 包含一个内部缓冲区,该缓冲区包含从流中读取的字节.内部计数器跟踪 read ...
随机推荐
- ffmpeg部分编译选项
-enable-neon (如果使用了arm公司提供的neon加速技术,则可以并行的读取多个元素.参考网址:http://www.cnblogs.com/hrlnw/p/3723072.html) ...
- DAY15-web框架本质及第一个Django实例
Web框架本质 我们可以这样理解:所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端. 这样我们就可以自己实现Web框架了. 半成品自定义web框架 impor ...
- Python之条件语句以及循环
Python代码的缩进规则.具有相同缩进的代码被视为代码块 缩进请严格按照Python的习惯写法:4个空格,不要使用Tab,更不要混合Tab和空格,否则很容易造成因为缩进引起的语法错误. 注意: if ...
- hibernate学习笔记(3)hibernate常用配置以及session对象
更改hibernate.cfg.xml的内容,常用配置有: <!-- 把hibernate运行时的SQL语句显示到控制台 --> <property name="sho ...
- 《Android应用性能优化》 第8章 图形
1.例子中 30个部件的xml setContentView 几乎占用了从onCreate() 到 onResume() 结束之前所有时间的99% 因为展开布局的开销很大.要尽量用不同的布局方式.比如 ...
- <c:set var="ctx" value="${pageContext.request.contextPath}" />的学习
${pageContext.request.contextPath},是获取当前根目录 set var="ctx",是给这个路径定义了一个变量,用的时候可以通过EL表达式获取:${ ...
- HTML5的头部、拨号、短信、邮件(转)
HTML5[语法要点] 一.头部设置 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <!--页面窗口自动调整到设备 ...
- 安装Fastqc软件遇到的坑
由于之前的HPC太难用了,所以决定搬家到十楼的工作站,于是就免不了配置必要的工作环境,其中一个少不了要安装的软件是就是fastqc,因为它太常用了. 我先是用conda安装,因为conda实在是太方便 ...
- rest-framework组件 之 认证与权限组件
浏览目录 认证组件 权限组件 频率组件 认证与权限组件 认证组件 局部视图认证 在app01.service.auth.py: class Authentication(BaseAuthenticat ...
- Entity Framework Tutorial Basics(31):Migration from EF 4.X
Migration from Entity Framework 4.1/4.3 to Entity Framework 5.0/6.0 To migrate your existing Entity ...