初识IO
体系
IO流原理及流的分类
节点流和处理流
输入流
-
InputStream 输入流
- FilelnputStream 文件
- BufferetInputStream 缓冲 节点和处理流
- ObjectlnputStream 对象 输入流
-
Reader 字符 读
- FileReader 文件 读
- BufferedReader 缓冲 读。节点和处理流
- InputStreamReader 输入流 读。转换流
输出流
-
OutputStream 字节
- FileOutputStream 文件
- BufferedOutputStream 缓冲。节点和处理流
- ObjectOutputStream 对象
-
Writer 字符
- FileWriterBuffer 文件
- BufferedWriter 缓冲
- OutputStreamWriter 输出流。转换流
Properties类
详细体系分类
字节流
- lnputStream
- FilelnputStream 文件输入流
- PipedInputStream
- **ObjectlnputStream ** 对象字节输入流
- ByteArraylnputStream
- SequencelnputStream
- FilterlnputStream 过滤输入
- BufferedlnputStream 缓冲字节输入流
- DigestinputStream
- DatalnputStream
- OutputStream
- FileOutputStream
- PipedOutputStream
- ObjectOutputStream
- ByteArrayOutputStream
- FilterOutputStream
- BufferedOutputStream
- DigestOutputStream
- DataOutputStream
- PrintStream
字符流
- Reader 字符输入流
- lnputStreamReader
- FileReader
- BufferedReader
- CharArrayReader
- FilterReader
- PipedReader
- StringReader
- lnputStreamReader
- Writer 字符输出流
- OutputStreamWriter
- FileWriter
- BufferedWriter
- CharArrayWriter
- FilterWriter
- PipedWriter
- PrintWriter
- StringWriter
- OutputStreamWriter
文件里的数据,相当于物品。
输入流 和 输出流,相当于 外卖小哥(需要通过外卖小哥 运输)
文件和文件流
文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文件,excel文件…都是文件。它既可以保存一张图片,也可以保持视频,声音.….
文件流
文件在程序中是以流的形式来操作的
java程序
- (内存)输出流
文件(磁盘)
反之:文件到java程序 为:输入流
- 比如 人喝水 就是输入
- 人 吐口水 是 输出
- 杯子是文件。水是数据。
- 人就是java程序,胃就好像是内容。
流:数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
文件的相关操作
创建文件对象相关构造器和方法相关方法
new File(String pathname)//根据路径构建一个File对象
new File(File parent String child)//根据父目录文件+子路径构建
new File(String parent,String child)//根据父目录+子路径构建
createNewFile 创建新文件
Serializable 接口
Comparable
- File
创建文件
直接new全路径
String filePath = "e:\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
\\news1.txt //这样写,如果项目在D盘,就创建到D盘根目录
news1.txt //这样写,如果idea打开的是:D:\代码\ 这个目录(目录下有多个项目)。那么就是在 \代码 目录下
//D:\代码\new4.txt
//注意了,这种写法如果使用 JUnit 会在往里一层。file.getAbsolutePath() 查看。/a.txt 和 \\a.txt junit和main一样。
//文件创建成功 D:\代码\chapter19\news1.txt
Panel.class.getResource("/com/hspedu/tankgame4/gif/bomb_1.gif")
//这种是在源文件下,如:src是源文件。就从 src/com/...下找。
//这种:/bomb_1.gif,就要放在src目录下
父+子创建
- 使用父文件+目录
File parentFile = new File("e:\\");
String fileName = "news2.txt";
//这里的file对象,在java程序中,只是一个对象
//只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
File file = new File(parentFile, fileName);
//String parentPath = "e:\\";
String parentPath = "e:/"; //这样写,也是行的
String fileName = "news4.txt";
File file = new File(parentPath, fileName);
获取文件的相关信息
获取文件的相关信息
getName、getAbsolutePath(绝对路径)、getParent、
length 字节大小、exists、isFile、isDirectory
//先创建文件对象
File file = new File("e:\\news44.txt");
//调用相应的方法,得到对应信息 news44.txt
System.out.println("文件名字=" + file.getName());
//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
//e:\news44.txt
System.out.println("文件绝对路径=" + file.getAbsolutePath());
//e:\
System.out.println("文件父级目录=" + file.getParent());
System.out.println("文件大小(字节)=" + file.length());//9 (输入了1-9)。如果utf-8,一个汉字对应3个字节。
System.out.println("文件是否存在=" + file.exists());//T
System.out.println("是不是一个文件=" + file.isFile());//T
System.out.println("是不是一个目录=" + file.isDirectory());//F
目录操作
目录的操作和文件删除
mkdir创建一级目录、
mkdirs创建多级目录、
delete删除空目录或文件
//判断 d:\\news1.txt 是否存在,如果存在就删除
String filePath = "e:\\news1.txt";
File file = new File(filePath);
if (file.exists()) {
if (file.delete()) {
System.out.println(filePath + "删除成功");
} else {
System.out.println(filePath + "删除失败");
}
} else {
System.out.println("该文件不存在...");
}
//判断 D:\\demo02 是否存在,存在就删除,否则提示不存在
//这里我们需要体会到,在java编程中,目录也被当做文件
String filePath = "D:\\demo02";
//其他都一样
//判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
String directoryPath = "D:\\demo\\a\\b\\c";
File file = new File(directoryPath);
if (file.exists()) {
System.out.println(directoryPath + "存在..");
} else {
if (file.mkdirs()) { //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()
System.out.println(directoryPath + "创建成功..");
} else {
System.out.println(directoryPath + "创建失败...");
}
}
IO原理和分类
Java IO流原理
-
I/O是lnput/Output的缩写,I/O技术是
[常实用的技术,用于处理数据传输。
如读/写文件,网络通讯等。 -
Java程序中,对于数据的输入/输出操作以”流(stream)”的方式进行。
-
java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方
法输入或输出数据
Java IO流原理
4.输入input:读取外部数据
(磁盘、光盘等存储设备的数据)到程序(内存)中。
- 也可能是网络
5.输出output:将程序(内存)
数据输出到磁盘、光盘等存储设备中
- 也可能输出到网络
流的分类
按操作数据单位不同分为:字节流(8 bit),字符流(按字符)
- 一个字符对应几个字节,和编码有关。utf-8 汉字对应3个
- 字节流 操作 二进制文件 更好 (声音 视频 word)。
按数据流的流向不同分为:输入流,输出流
按流的角色的不同分为:节点流,处理流/包装流
- 节点流 处理流:Buffered
- 包装流 转换流:InputStreamReader 和 OutputStreamWriter
(抽象基类)
字节流:分为输入 输出
字符流:同样分为 输入 输出
输入流
InputStream
Reader
输出流
OutputStream
Writer
- Java的IO流共涉及40多个类,实际上非常规则
都是从如上4个抽象基类派生的,
2)由这四个类派生出来的子类名称都是以其父类名作为子类名后缀
public abstract class OutputStream implements Closeable, Flushable {}
常用类
InputStream
InputStream:字节输入流
InputStream:抽象类是所有类字节输入流的超类
常用的子类
- FilelnputStream:文件输入流
- BufferedInputStream:缓冲字节输入流
- 父类:FilterlnputStream 过滤输入
- ObjectlnputStream:对象字节输入流
FileInputStream(File file);
//通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File对象file指定。
FileInputStream (FileDescriptor fd0bj)
//通过使用文件描述符f dobj创建一个 FileIrputStrean,该文件描述符表示到文件系统中某个实际文件的现有连接。
FileInput Stream(String name)
//通过打开一个到实际文件的连接来创建一个FileInputStrean,该文件通过文件系统中的路径名name指定。
read()
//从此输入流中读取一个数据字节。
//返回值:从该输入流读取一个字节的数据。如果没有输入可用,
//数据的下一个字节,如果达到文件的末尾,-1
int read(byte[] b)
//从此输入流中将最多b.length个字节的数据读入一个 byte数组中。此方法将阻止。直到某些输入可用。
int read (byte[] b,int off, int len)
//从此输入流中将最多len个字节的数据读入一个 byte数组中。
skip(long n)
//从输入流中跳过并丢弃n个字节的数据。
FileInputStream
(字节输入流 文件--> 程序)
/**
* 演示读取文件...
* 单个字节的读取,效率比较低
* -> 使用 read(byte[] b)
*/
@Test
public void readFile01() {
String filePath = "e:\\hello.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。
//如果返回-1 , 表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char)readData);//转成char显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源.
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 使用 read(byte[] b) 读取文件,提高效率
*/
@Test
public void readFile02() {
String filePath = "e:\\hello.txt";
//字节数组
byte[] buf = new byte[8]; //一次读取8个字节.
int readLen = 0;
FileInputStream fileInputStream = null;
//创建 FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
//如果返回-1 , 表示读取完毕
//如果读取正常, 返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
//buf 的值 假如是 hello,word。第一次数组的 0位置为 104为h,101为e。读取到的是 ASCII码的值
System.out.print(new String(buf, 0, readLen));//显示
}
}
FileOutputStream
FileOutputStrean (File file)
File0utput Strean (File file,boolean append)
//创建一个向指定File 对象表示的文件中写入数据的文件输出流。
FileoutputStrean (String name)
//创建一个向具有指定名称的文件中写入数据的输出文件流。
void write(byte[] b)
void write(byte[] b,int off, int len)
//将指定byte数组中从偏移量off开始的 len个字节写入此文件输出流。
void writer(int b)
//将指定字节写入此文件输出流。
/**
* 演示使用FileOutputStream 将数据写到文件中,
* 如果该文件不存在,则创建该文件
*/
//创建 FileOutputStream对象
String filePath = "e:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
//得到 FileOutputStream对象 对象
//老师说明
//1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
//2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
fileOutputStream = new FileOutputStream(filePath, true);
//写入一个字节
//fileOutputStream.write('H');
//写入字符串
String str = "hsp,world!";
//str.getBytes() 可以把 字符串-> 字节数组
//fileOutputStream.write(str.getBytes());
/*
write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流
*/
fileOutputStream.write(str.getBytes(), 0, 3);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
文件拷贝
在完成程序时,应该是读取部分数据,就写入到指定文件,这里使用循环
//完成 文件拷贝,将 e:\\Koala.jpg 拷贝 c:\\
//思路分析
//1. 创建文件的输入流 , 将文件读入到程序
//2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件.
String srcFilePath = "e:\\Koala.jpg";
String destFilePath = "e:\\Koala3.jpg";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream = new FileOutputStream(destFilePath);
//定义一个字节数组,提高读取效果
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = fileInputStream.read(buf)) != -1) {
//读取到后,就写入到文件 通过 fileOutputStream
//即,是一边读,一边写
fileOutputStream.write(buf, 0, readLen);//一定要使用这个方法
}
System.out.println("拷贝ok~");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭输入流和输出流,释放资源
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
文件拷贝自动关流
try (FileInputStream fi = new FileInputStream("e:\\1.jpg");
FileOutputStream fo = new FileOutputStream("e:\\2.jpg")) {
byte[] b = new byte[1024];
int len;
while ((len = fi.read(b)) != -1) {
fo.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
FileReader 和 FileWriter
FileReader和 FileWriter是字符流,即按照字符来操作io
FileReader相关方法:
1) new FileReader(File/String)
2) read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
3) read(char[l):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回 -1
相关APl:
1) new String(char[]):将char[]转换成String
2) new String(char[1,off,len]):将char[的指定部分转换成String
- Reader 字符输入流
- lnputStreamReader
- FileReader
- lnputStreamReader
- Writer 字符输出流
- OutputStreamWriter
- FileWriter
- OutputStreamWriter
public class InputStreamReader extends Reader{}
FileWriter常用方法
1) new FileWriter(File/String):覆盖模式,相当于流的指针在首端
2) new FileWriter(File/String,true):追加模式,相当于流的指针在尾端3) write(int):写入单个字符
4) write(char[]):写入指定数组
5) write(char[],off,len):写入指定数组的指定部分6) write (string):写入整个字符串
7) write(string,off,len):写入字符串的指定部分
相关APl: String类:toCharArray:将String转换成char[]
注意:
FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件!
FileReader
System.out.println("~~~readFile02 ~~~");
String filePath = "e:\\story.txt";
FileReader fileReader = null;
int readLen = 0;
char[] buf = new char[8];
//1. 创建FileReader对象
try {
fileReader = new FileReader(filePath);
//循环读取 使用read(buf), 返回的是实际读取到的字符数
//如果返回-1, 说明到文件结束
while ((readLen = fileReader.read(buf)) != -1) {
System.out.print(new String(buf, 0, readLen));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
String filePath = "e:\\story.txt";
FileReader fileReader = null;
int data = 0;
//1. 创建FileReader对象
fileReader = new FileReader(filePath);
//循环读取 使用read, 单个字符读取
while ((data = fileReader.read()) != -1) {
System.out.print((char) data);
}
FileWriter
public static void main(String[] args) {
String filePath = "e:\\note.txt";
//创建FileWriter对象
FileWriter fileWriter = null;
char[] chars = {'a', 'b', 'c'};
try {
fileWriter = new FileWriter(filePath);//默认是覆盖写入
// 3) write(int):写入单个字符
fileWriter.write('H');
// 4) write(char[]):写入指定数组
fileWriter.write(chars);
// 5) write(char[],off,len):写入指定数组的指定部分
fileWriter.write("韩顺平教育".toCharArray(), 0, 3);
// 6) write(string):写入整个字符串
fileWriter.write(" 你好北京~");
fileWriter.write("风雨之后,定见彩虹");
// 7) write(string,off,len):写入字符串的指定部分
fileWriter.write("上海天津", 0, 2);
//在数据量大的情况下,可以使用循环操作.
} catch (IOException e) {
e.printStackTrace();
} finally {
//对应FileWriter , 一定要关闭流,或者flush才能真正的把数据写入到文件
//老韩看源码就知道原因.
/*
看看代码
private void writeBytes() throws IOException {
if (var3 > 0) {
if (this.ch != null) {
assert this.ch.write(this.bb) == var3 : var3;
} else {
//注意了:***************这里底层用的 依然是 FileOutputStream
this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
}
}
this.bb.clear();
}
*/
try {
//fileWriter.flush();,最终调用的 依然是 writeBytes
//关闭文件流,等价 flush() + 关闭
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("程序结束...");
}