一、Java中流的分类
1、按流向区分
输入流:InputStream和Reader作为基类
输出流:OutputStream和Writer作为基类
2、按照处理数据单元划分
字节流:InputStream、OutputStream作为基类
字符流:Reader、Writer作为基类
二、字节流
字节流分输入字节流InputStream和输出字节流OutputStream。它们常用子类为FileInputStream和FileOutputStream。
1、InputStream类常用方法
int read( ):从输入流中读取下一个字节数据
int read(byte[] b):从输入流中读取数据,并将数据存储在缓冲区数组b中,返回实际读取的字节数
int read(byte[] b,int off,int len):从输入流中读取最多len长度的字节,保存到字节数组b中,保存的位置从off开始
void close( ):关闭输入流
int available():可以从输入流中读取的字节数目
子类FileInputStream常用的构造方法
FileInputStream(File file)
FileInputStream(String name)
2、OutputStream类常用方法
void write(int c):将指定的字节数据写入此输出流中
void write(byte[] buf):将数组buf中的所有字节写入此输出流中
void write(byte[] b,int off,int len):将字节数组中从偏移量off开始的长度为len的字节数据输出到输出流中
void close():关闭输出流
void flush():强制把缓冲区的数据写到输出流中
3、代码实现
使用FileInputStream读取文件
//1、引入资源
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamDemo {
public static void main(String[] args) {
FileInputStream fis=null;
try {
//2、创建对象
fis=new FileInputStream("d:/1117/b.txt");
System.out.println("可以读取到的字节数是:"+fis.available());
//3、利用read()方法读取文件
int tmp;
while ((tmp=fis.read())!=-1){
System.out.print((char)tmp);
}
//方法二
// byte[] b=new byte[fis.available()];
// int tmp;//读取到的字节数
// while ((tmp=fis.read(b))!=-1){
// for (int i = 0; i < tmp; i++) {
// System.out.print((char)b[i]);
// }
// }
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
//4、关闭流
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用FileOutputStream写入文件
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDemo {
public static void main(String[] args) {
FileOutputStream fos=null;
try {
fos=new FileOutputStream("a.txt");
String info="hello world!";
byte[] b=info.getBytes();
try {
fos.write(b);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}