标准输入输出流
- 标准输入、输出流也是处理流之一
- System.in和System.out分别代表了系统标准的输入和输出设备
- 默认输入设备:键盘;输出设备:显示器(控制台)
- System类的setIn(InputStream is)/ setOut(printStream ps)方式重新指定输入和输出
package www.bh.c.iotest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test14 {
public static void main(String[] args) {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while (true){
System.out.println("请输入字符串:");
String s = br.readLine();
if ("e".equalsIgnoreCase(s)||"exit".equalsIgnoreCase(s)){
System.out.println("程序结束");
break;
}
String s1 = s.toUpperCase();
System.out.println(s1);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 总结:
- 输入过程:
- 1.创建File类的对象,指明读取的数据的来源(要求此文件一定要存在)
- 2.创建相应的输入流,将File类的对象作为参数,传入流的构造器中
- 3.具体的读入过程:创建相应的byte[] 或char[]
- 4.关闭流资源
- 输出过程:
- 1.创建File类的对象,指明写出的数据的位置(不要求此文件一定要存在)
- 2.创建相应的输出流,将File类的对象作为参数,传入流的构造器中
- 3.具体的写出过程:write(char[]/byte[] buffer,0,len)
- 4.关闭流资源
打印流
- 打印流也是处理流的一种,实现将基本数据类型的数据格式转化为字符串输出
- PrintStream()和PrintWriter()
- 提供了一系列重载的print()和printIn()
数据流
- 打印流也是处理流的一种,用于读取和写出基本数据类型、String类的数据
- DataInputStream和DataOutputStream
- 以上两个类分别“套接”在InputStream和OutputStream子类的流上
package www.bh.c.iotest;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test15 {
public static void main(String[] args) {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("calss\\hello1.txt",true));
dos.writeUTF("Java");
dos.flush();
dos.writeInt(18);
dos.flush();
dos.writeBoolean(true);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos!=null){
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package www.bh.c.iotest;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Test16 {
public static void main(String[] args) {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("calss\\hello1.txt"));
String s=dis.readUTF();
int age=dis.readInt();
boolean isMale=dis.readBoolean();
System.out.println("name:"+s);
System.out.println("age:"+age);
System.out.println("isMale:"+isMale);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis!=null){
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}