IO流
1.文件
文件是保存数据的地方,可以保存一张图片,也可以保存视频、声音、文本文档等
1.1 文件流
文件在程序中是以流的形式来操作的
流:数据在数据源(文件)和程序(内存)之间经历的路径
输入流 : 数据从数据源(文件)到程序(内存)的路径
输出流 : 数据从程序(内存)到数据源(文件)的路径
1.2 创建文件
- new File(String pathname):根据路径构建一个File对象
- new File(File parent,String child):根据父目录文件+子路径构建
- new File(String parent,String child):根据父目录+子路径构建
- file.createNewFile:这一步才是创建新文件
@Test
public void createFile() {
File file = new File("d:\\news.txt");
try {
file.createNewFile();
System.out.println("文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
1.3 获取文件相关信息
- getName:获取文件名
- getAbsolutePath:获取文件的绝对路径
- getParent:获取文件父级目录
- length:获取文件(字节)大小
- exists:判断文件是否存在
- isFile:判断是否是文件
- isDirectory:判断是否是文件夹
1.4 目录操作
在java编程中,目录也被当作文件,也就是说,文件可以表示文件和目录
mkdir
:创建一级目录mkdirs
:创建多级目录delete
:删除空目录或文件
@Test
public void dir(){
File file = new File("d:\\news\\a\\b\\c");
if(file.exists()){
if(file.delete())
System.out.println("文件删除成功!");
}else {
if(file.mkdirs()) //创建多级目录
System.out.println("目录创建成功!");
}
}
2.IO流原理及流的分类
2.1 IO流原理
- l/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输如读/写文件,网络通讯等。
- Java程序中,对于数据的输入/输出操作以”流(stream)”的方式进行
- java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
- 输入input: 读取外部数据(磁盘、光盘等存储设备的数据)到程序 (内存) 中
- 输出output: 将程序 (内存) 数据输出到磁盘、光盘等存储设备中
2.2 流的分类
- 按操作数据单位不同分为:字节流(8 bit)二进制文件,字符流(按字符)文本文件
- 按数据流的流向不同分为:输入流、输出流
- 按流的角色的不同分为:节点流。处理流/包装流
(抽象基类) | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream |
Reader |
输出流 | OutputStream |
Writer |
3.字节流
3.1 FileInputStream 文件输入流
案例:把news.txt的内容通过FileInputStream读取,然后在控制台打印。
@Test
public void readFile() {
int readLength = 0; //每次读取的字节长度
File file = new File("d:\\news.txt");
byte[] bytes = new byte[8]; //一次读8个字节
FileInputStream in = null;
try {
in = new FileInputStream(file);
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while ((readLength = in.read(bytes)) != -1){
System.out.print(new String(bytes,0,readLength));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.2 FileOutputStream 文件输出流
案例:向 news.txt 追加 hello,world!
@Test
public void writeFile(){
FileOutputStream out = null;
try {
//文件不存在将创建,true表示追加
out = new FileOutputStream("d:\\news.txt",true);
//写入字符串
String str = "hello,world!";
//str.getBytes() 可以把字符串 -> 字节数组
out.write