按照流向划分为输入流和输出流
输入流:就是以程序为中心点,硬盘上的文件内容流入到程序中可以存储数据的东西中比如说数组,用read方法
输出流:就是以程序为中心点,程序中的数组或者其他的可以存储数据的东西中的内容输出到硬盘文件中,用write方法,需要用flush方法刷新一下,确保程序中的数组内容写出到硬盘文件中
按照传输的数据划分为字节流和字符流
字节流:二进制,可以一切文件 包括 纯文本 doc 音频、视频等等
字符流:文本文件,只能处理纯文本
用字节流就行
文件输入流实例:
package com.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class demo5 {
public static void main(String args[]){
//1、建立联系 File对象
File src =new File("F:/ld/lzy.txt");
//2、选择流
InputStream is =null; //提升作用域
try {
is =new FileInputStream(src);
//3、操作 不断读取 缓冲数组
byte[] car =new byte[1024];
int len =0; //接收 实际读取大小
//循环读取
StringBuilder sb =new StringBuilder();
while(-1!=(len=is.read(car))){
//输出 字节数组转成字符串
String info =new String(car,0,len);//数组转字符串
sb.append(info);
}
System.out.println(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取文件失败");
}finally{
try {
//4、释放资源
if (null != is) {
is.close();
}
} catch (Exception e2) {
System.out.println("关闭文件输入流失败");
}
}
}
}
文件输出流实例:
package com.java;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class demo6 {
public static void main(String args[]){
File dest=new File("F:/ld/Lzy.txt");
OutputStream os=null;
try {
os=new FileOutputStream(dest,true);
String str="ni shi yi ge da sha bi";
byte[] data=str.getBytes();//字符串转数组
os.write(data,0,data.length);
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件未找到");
}catch (IOException e) {
System.out.println("文件写出失败");
e.printStackTrace();
}finally {
if(null!=os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭输出流失败");
}
}
}
}
}