流
1、流是一组有序的数据序列;
2、以先进先出方式发送信息的通道
按流向分
输出流
OutputStream
InputStream
输入流
Reader
Writer
按处理数据单元分
字节流
字节输入流InputStream基类
int read();
int read(byte[ ] b);
int read(byte[ ] b,int off,int len);
void close();
int available();
FileInputStream reader =null;
try{
reader = new FileInputStream("myfile/cc.txt");
byte[] b = new byte[1024]; //字节读取到数组中
int len ; //读取到的字节数
while ((len=reader.read(b))!=-1){
for (int i = 0; i <len ; i++) {
System.out.print((char) b[i]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字节输出流OutputStream基类
void write(int b);
void write(byte[ ] b);
void write(byte[ ] b,int off,int len);
void close();
void flush();强制把缓冲区的数据写出输出流中
FileOutputStream writer =null;
try{
writer = new FileOutputStream("myfile/cc.txt",true) ; //向原文件追加
String info = "大数据";
byte[] infos =info.getBytes(); //将字符串转换为字节数组
writer.write(infos);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
字符流
字符输入流Reader基类
子类:BufferReader
int read();
int read(char[ ] c);
int read(char[ ] c,int off,int len);
void close();
FileReader reader1 =null;
BufferedReader reader2 = null;
try{
reader1 = new FileReader("myfile/cc.txt") ;
reader2 = new BufferedReader(reader1);
String s =null;
while ((s=reader2.readLine())!=null){
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader2.close();
reader1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符输出流Writer基类
子类:BufferWriter
void write(String str);
void write(String str,int off,int len);
void close();
void flush();强制把缓冲区的数据写出输出流中
File file = new File("myfile/aa.txt");
FileWriter writer2 =null;
BufferedWriter writer3 =null;
try{
writer2 = new FileWriter(file,true) ;
writer3 = new BufferedWriter(writer2);
writer3.write("大数据");
writer3.newLine(); //换行
writer3.write("大数据");
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer3.close();
writer2.close();
} catch (IOException e) {
e.printStackTrace();
}
}