一、标准的输入输出流
1、标准输入流System.in,默认从键盘输入
标准输出流System.out,默认输出到控制台
2、内部的setIn(InputStream in)和setOut(PrintStream out)可以重新定向流。
3、练习:从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序。
public static void main(String[] args){
BufferedReader bfr = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
bfr = new BufferedReader(isr);
while(true){
System.out.println("请输入字符串:");
String date = bfr.readLine();
if("e".equalsIgnoreCase(date) || "exit".equalsIgnoreCase(date)){
System.out.println("退出程序");
break;
}
String upperStr = date.toUpperCase();
System.out.println(upperStr);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(bfr != null){
try {
bfr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
测试结果:

二、打印流PrintStream和PrintWrite
1、说明:
提供了一些列重载的print()和println()方法。System.out返回的是PrintStream的实例。
2、练习
@Test
public void test2(){
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
ps = new PrintStream(fos, true);
if (ps != null) {// 把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i = 0; i <= 255; i++) { // 输出ASCII字符
System.out.print((char) i);
if (i % 50 == 0) { // 每50个数据一行
System.out.println(); // 换行
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}
三、数据流DataInputStream和DataOutputStream
1、作用
DataOutputStream将内存中的基本数据类型及字符串写入到文件中
DataInputStream将保存在文件中的基本数据类型读出到内存中。
2、示例代码
@Test
public void tst3() throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("刘强东");
dos.flush();//刷新操作,一旦执行就将数据写入文件
dos.writeInt(21);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.close();
}
/*
DataInputStream将保存在文件中的基本数据类型读出到内存中。
注意点:读取数据的顺序要与当初写入数据类型的顺序相同
*/
@Test
public void tst4() throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name = " + name);
System.out.println("age = " + age);
System.out.println("isMale = " + isMale);
dis.close();
}
