- 流是Java处理输入输出的方式
- 流的基础类——以字节(byte)形式
InputStream
OutputStream
例
public class Main {
public static void main(String[] args){
System.out.println("请输入:");
//定义一个字节数组
byte[] buffer = new byte[1024];
try {
int len = System.in.read(buffer);
String s = new String(buffer,0,len);
System.out.println("读到了"+len+"字节");//回车也算一个,只不过看不见
System.out.println(s);
System.out.println("s的长度是"+s.length());
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
请输入:
画眉深浅入时无
读到了22字节
画眉深浅入时无
s的长度是8
- 直接读写文件——文件流基本类
FileInputStream
FileOutputStream
例
public class Main {
public static void main(String[] args){
System.out.println("请输入:");
//定义一个字节数组
byte[] buffer = new byte[1024];
try {
System.in.read(buffer);
FileOutputStream out = new FileOutputStream("a.dat");
out.write(buffer);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
控制台无输出,产生了一个a.dat文件
- 过滤器流
前面看到的流都只能处理单个字节
但当遇到一个int四个字节时?
过滤器流——在已经有的文件流的基础上增加一层层过滤器流
public class Main {
public static void main(String[] args){
//定义一个字节数组
byte[] buffer = new byte[1024];
try {
//写文件
DataOutputStream out = new DataOutputStream(//处理基本数据类型
new BufferedOutputStream(//起缓冲作用
new FileOutputStream("b.dat")));
int i = 0xcafebabe;//十六进制(使用十进制也仍然会以十六进制存储)
out.writeInt(i);
out.close();
//再读文件(以十进制输出,给人来看)
DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("b.dat")));
int j = in.readInt();
System.out.println(j);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 文本处理基本类
InputStream/OutputStream 只能够处理字节
DataInputStream/ DataOutputStream 只能处理基本数据类型
二进制数据采用DataInputStream/ DataOutputStream
文本数据采用Reader/Writer
(dat人不能直接读,需要工具软件,a.txt人可以直接读)
public class Main {
public static void main(String[] args){
try {
//写文件
PrintWriter out = new PrintWriter(
new BufferedWriter(//起缓冲作用
new OutputStreamWriter(//起桥梁作用
new FileOutputStream("b.txt"))));
int i = 123456;
out.println(i);
out.close();
//读源代码文件
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream("src/IOstream/Main.java")));
String line;
//当没有读到文件末尾
while((line = in.readLine())!= null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- PrintWriter对输出做控制
format(“格式”,…);
printf(“格式”,…);//和C基本一致
print(各种基本类型);
println(各种基本类型);
在InputStream或Reader上建立一个Scanner对象
可以从流中的文本中解析出以文本表达的各种基本类型
next…()
如何选择类来读数据