今天学习了
从控制台读取字符串
从标准输入读取一个字符串需要使用 BufferedReader 的 readLine() 方法。
它的一般格式是:
String readLine( ) throws IOException
下面的程序读取和显示字符行直到你输入了单词"end"。
BRReadLines.java 文件代码:
//使用 BufferedReader 在控制台读取字符 import java.io.*; public class BRReadLines { public static void main(String args[]) throws IOException { // 使用 System.in 创建 BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'end' to quit."); do { str = br.readLine(); System.out.println(str); } while (!str.equals("end")); } }
以上实例编译运行结果如下:
Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end
JDK 5 后的版本我们也可以使用 Java Scanner 类来获取控制台的输入。
控制台输出
在此前已经介绍过,控制台的输出由 print( ) 和 println() 完成。这些方法都由类 PrintStream 定义,System.out 是该类对象的一个引用。
PrintStream 继承了 OutputStream类,并且实现了方法 write()。这样,write() 也可以用来往控制台写操作。
PrintStream 定义 write() 的最简单格式如下所示:
void write(int byteval)
该方法将 byteval 的低八位字节写到流中。
实例
下面的例子用 write() 把字符 "A" 和紧跟着的换行符输出到屏幕:
WriteDemo.java 文件代码:
import java.io.*; //演示 System.out.write(). public class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); } }
运行以上实例在输出窗口输出 "A" 字符
A
注意:write() 方法不经常使用,因为 print() 和 println() 方法用起来更为方便。