输入Input —— 读文件read 网络上传
输出Output —— 写文件write 网络下载
以字节为单位 所有类型的文件 视频文件 音频文件 图像文件 文本文件 —— >抽象类 InputStream OutputStream ——> 实现类 FileInputStream FileOutputStream
以字符为单位 仅限于文本文件——>抽象类 Reader Writer ——>实现类 FileReader FileWriter
类的构造方法
FileOutputStream类的构造方法 - 方法参数 String 或 File
FileOutputStream fos = new FileOutputStream("c:\\a.txt");
File file = new File("c:\\a.txt");
FileOutputStream fos = new FileOutputStream(file,true); //第二个参数 是否append追加续写
FileWriter类的构造方法
FileWriter fw = new FileWriter("c:\\1.txt");
FileInputStream类的构造方法
FileInputStream fis = new FileInputStream("c:\\a.txt");
FileReader类的构造方法
FileReader fr = new FileReader("c:\\1.txt");
类的成员方法
FileOutputStream类的“写”方法
//写1个字节 Java中 ,byte类型的数值范围 -128~127
fos.write(97);//写字节数组
byte[] bytes = {65,66,67,68,69,70};
fos.write(bytes);//写字节数组的一部分,开始索引,写几个
fos.write(bytes, 2, 3);
fos.write("hello\r\n world".getBytes());//String类的getBytes()方法 将字符串转为字节数组
FileInputStream类的“读”方法
int len = fis.read();//每执行一次read() 就自动读取下一字节 切勿多次书写read()
byte[] b = new byte[1024];
int len = fis.read(b);//读到文件末尾的结束符时 read()方法直接返回-1 len 每次读取 真实有效字节的数目 每次读取到的字节存储在字节数组b中
int len = 0;//接受read方法的返回值
while( (len = fis.read()) != -1){
System.out.print((char)len);
}
//创建字节数组
byte[] b = new byte[1024];//每次读取1024字节 即1kb 以提高文件读取的效率
int len = 0;while( (len = fis.read(b)) !=-1){
System.out.print(new String(b,0,len));//String类的 字节数组参数 构造方法
}
FileWriter类的“写”方法
//写1个字符
fw.write(100);
fw.flush();//字符输出流 写数据的时候,必须要运行此刷新缓存的功能//写字符数组
char[] c = {'a','b','c','d','e'};
fw.write(c);
fw.flush();//写字符数组一部分
fw.write(c, 2, 2);
fw.flush();//写字符串
fw.write("hello");
fw.flush();
FileReader类的“读”方法
char[] ch = new char[1024];//字符数组 java中 一个字符占2个byte字节!
int len = 0;while((len = fr.read(ch))!=-1){
System.out.print(new String(ch,0,len));
}