- 스트림은 Java가 입력 및 출력을 처리하는 방식입니다.
- , 시냇물의 기본 클래스
의 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文件
- 필터 스트림
앞에서 본 스트림은 단일 바이트 만 처리 할 수
있지만 4 바이트의 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 ( "format",…);
printf ( "format",…); // 기본적으로 C와 동일합니다
print (다양한 기본 유형);
println (다양한 기본 유형);
InputStream 또는 Reader에 Scanner 객체를 생성하여 다음
스트림의 텍스트에서 텍스트로 표현 된 다양한 기본 유형을 구문 분석 할 수 있습니다
... ()
데이터를 읽을 클래스를 선택하는 방법