IO流的使用
流的分类
- 按流向分为:输入和输出
输入:InputStream、Reader
输出:OutputStream、Writer - 按类型分为:字节和字符
字节流:InputStream、OutputStream
字符流:Reader、Writer - 按功能分为:节点流和处理流
文件IO流的构造方法
输入流:FileReader(File file) 或FileInputStream(File file)
输出流 : |
---|
FileWriter(File file) |
FileOutputStream(File file) |
FileWriter(File file, boolean append) |
FileWriter(File file, boolean append) |
常用方法
InputStream类 | Reader |
---|
available():获取当前流中的可读字节数 | read():读取并返回一个字符 |
close():关闭此流 | close():关闭此流 |
read():从流中读取一个字节,返回读取到的字节 | read(char[] c):将从流中读取的字符存储到字符数组 |
read(byte[] b,int offset,int len):将流中读取奥的字节存入到指定的字节数组中(跳过offset个字节存储,存储长度为len),读取不到返回-1 | read(char[] c,int offset,int len):将从流中读取的字符存入字符数组(跳过offset个字节,写入len长) |
| ready():返回此流是否准备好被读取的状态 |
OutputStream类 | Writer |
---|
write(byte[] b):将字节数组中的内容写入输出源(文件,网络,内存) | append(char c):向流中追加一个字符 |
write(byte[] b,int offset,int len):将字节数组中的内容从offset开始写入len长到输出源 | append(CharSequence c):向流中追加一个字符序列(字符串) |
write(int b):将一个字节写入输出源 | witer(String s):写入一个字符串到目标输出源 |
flush():将流中的数据强制刷新到输出源 | witer(char[] c):写入字符数组到目标输出源 |
close():关闭此流 | |
字节流与字符流
字节流 | 字符流 |
---|
所谓字节流,其实就是将数据以字节为单位进行读写相关操作,字节流一般用于对于一些二进制文件(图片,音频,视频等)进行读写操作 | 字符流,顾名思义,是以字符的形式对输入输出源操作,通常情况下一个字符表示两个字节 |
文件拷贝功能的实现
public class FileCopy {
/**
* 将源文件拷贝到目标目录中
* @param sourceFile 源文件(标准文件)
* @param targetDir 目标目录(目录)
*/
public void copy(File sourceFile,File targetDir){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//获取源文件的输入流
fis = new FileInputStream(sourceFile);
//获取目标文件的输出流
fos = new FileOutputStream(new File(targetDir,sourceFile.getName()));
//声明字节缓冲区
byte[] b = new byte[1024];
//声明变量存储真实读取长度
int len = 0;
//循环读取以及写入
while((len = fis.read(b)) != -1){
fos.write(b,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
//关闭资源
if(fos != null){
fos.close();
}
if(fis != null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
File source = new File("拷贝文件");
File target = new File("要拷贝到的地址");
new FileCopy().copy(source, target);
}
}