标准输入输出流
System.in和System.out分别代表了系统标准的输入和输出设备。默认的输入/输出设备为:键盘/显示器
- System.in:类型是InputStream。
- System.out:类型是PrintStream,PrintStream是OutputStream的子类FilterOutputStream的子类。
重定向:System类的setIn()和setOut()可以重新指定输入和输出的位置。
- public void setIn(InputStream in)
- public void setOut(PrintStream out)
示例:从控制台输入字符串,将读取到的字符串整行转换为大写,然后继续进行输入操作。当输入的是exit时,退出程序。
public class SystemInAndOutTest {
// 从控制台输入字符串,将读取到的字符串整行转换为大写,然后继续进行输入操作。当输入的是exit时,退出程序。
public static void main(String[] args) {
BufferedReader br = null;
try {
// 从键盘传入的是字节输入流,用转换流转换为字符输入流
InputStreamReader isr = new InputStreamReader(System.in);
// 涉及到读取一整行的字符串,可以使用BufferedReader的readLine()
br = new BufferedReader(isr);
while(true){
System.out.println("请输入字符串:");
String s = br.readLine();
if (s.equalsIgnoreCase("exit")){
System.out.println("退出程序!");
break;
}
System.out.println(s.toUpperCase());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
这里涉及了一点转换流的作用,之前没体现出来,这里体现出来了。
打印流
实现将基本数据类型的数据格式转化为字符串输出。
-
PrintStream
-
PrintWriter
- 提供了一系列重载的print()和println(),用于多种数据类型的输出。
- PrintStream和PrintWriter的输出不会抛出IOException异常。
- PrintStream和PrintWriter有自动flush(自动刷新)功能。
- System.out返回的是PrintStream的实例。
数据流
持久化基本数据类型和String类型的数据。为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。(读取或写入基本数据类型的变量或字符串)
- DataInputStream
- DataOutputStream
示例:test1:将基本类型和String类型写入到硬盘中。
public class DataOutputStreamTest {
@Test
public void test1(){
DataOutputStream dos = null;
try {
// 将基本数据类型的变量和String类型的变量写入到data.txt中
dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("王德发");
dos.flush();
dos.writeInt(21);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.writeChar('A');
dos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null){
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
写入到硬盘,直接在硬盘查看文件。
由此可以看出,是查看不了的,得用数据流去读取。
test2():将test1写入到硬盘的数据读出来。
@Test
public void test2(){
DataInputStream dis = null;
try {
// 将刚才写入到硬盘的数据读出来
dis = new DataInputStream(new FileInputStream("data.txt"));
System.out.println("name:" + dis.readUTF());
System.out.println("age:" + dis.readInt());
System.out.println("Study is Happy? " + dis.readBoolean());
System.out.println("A or B or C? " + dis.readChar());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis != null){
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意:读取不同类型的数据要与当初写入文件保存数据时的顺序一致。否则报异常(EOFException)。