超详细基础文件操作
目录
1. ObjectOutputStream,可以对数据进行序列化操作
让我们一起努力吧
前言
初学Java,对于文件的基本操作不太清楚的小伙伴们,可以了解一下我的理解。
一、文件是什么?
文件就是保存数据的地方。
二、创建文件
在JDK8 中 浏览File类的构造器发现有四种,也就是可以有四种方式来创建File对象。
以第三种为例
/**
* 在E盘创建 paidax.text 文件
*/
File pathfile = new File("e://");//父目录
String filename = "paidax.text";//子文件
File file = new File(pathfile, filename);
try {
file.createNewFile();//调用该方法,创建文件
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
三、文件中的常用操作
返回值 | 方法名 | 概要解析 |
long | file.length() | 返回文件的字节大小 |
String | file.getName() | 获得文件的名称 |
String | file.getAbsolute | 获得该文件的绝对路径 |
String | file.getParent() | 获得该文件的父目录 |
boolean | file.exists() | 判断该路径是否为目录/文件 |
boolean | file.isFIle() | 判断该路径是否是一个普通文件 |
boolean | file.isDirectory | 判断该路径是否为目录 |
boolean | file.canWrite() | 判断该路径所表示的文件是否可写操作 |
boolean | file.canRead() | 判断该路径所表示的文件是否可读操作 |
boolean | file.delete() | 删除由此抽象路径名表示的文件或目录。 如果此路径名表示目录,则目录必须为空才能删除。 |
boolean | file.creatNewFile() | 创建该抽象路径所表示的文件/目录,返回true,则创建成功,false 表示该文件已经存在 |
boolean | file.renamTo(File dest) | 重命名该文件,true,则成功,否则,返回false |
四、Java中流的概念
1.流的分类
(1)按流向分类
1. 输入流(文件或网络中的数据传入到程序中)
2. 输出流(将程序中的内容传输到网络或文件中)
(2)按数据单位分类
1. 字节流(一个字节8个bit)针对二进制文件(图片/视频)
2. 字符流(文本文件)
(3)按流的角色不同
1. 节点流
2. 包装流
五、Java IO流原理及分类
(1)IO技术用于数据传输,和网络通信等。
在Java中IO流的分类
1. 字节输入、输出流
字节输入流---FileInputStream常用的方法
1. 创建字节输入流
(1)new FileInputStream(file/ String)
2. read() 读取单个字节,到文件结束返回 -1
3. read (byte[] b) 一次性读入b.length()个字节,数组b作为缓存区,读入到文件结束返回 -1
4. read (byte[] b,int off,int len) off 为起始位置,len 作为一次性读入最大的字节数,数组b作为缓存区,读入到文件结束返回 -1
字节输出流---FileOutputStream常用的方法
1. 创建字节输出流
new FileOutputStream(file/String)//覆盖模式
new FileOutputStream(file/String,true)//追加模式
2. write()一次性写入一个字节
3. write(byte [] b)一次性写入b.length()字节
4. read (byte[] b,int off,int len) off 为起始位置,len 作为一次性写入最大的字节数,数组b作为缓存区,到文件结束返回 -1
案例: 应用字节输入输出流,完成文件的拷贝
1 . 找到对应的文件,用输入流读入到程序中,再将数据输出到另一个文件中,并创建该文件
File file = new File("e:\\FileCopy01.jpg");
byte[] b = new byte[1024];
File file1 = new File("e:\\FileCpoy02.jpg");//拷贝到这个文件
FileOutputStream fileOutputStream = new FileOutputStream(file1);
FileInputStream fileInputStream = new FileInputStream(file);
int content = 0 ;
try {
while ((content = fileInputStream.read(b)) != -1) { //一次性读入b.length()个字节,提高读数据的效率
fileOutputStream.write(b,0,content);
}
file1.createNewFile();
System.out.println("文件拷贝成功");
} catch (IOException e) {
e.printStackTrace();
}
finally {
fileInputStream.close();//关闭文件
fileOutputStream.close();
}
}
2、字符输入/输出流
1. 字符输入流-------FileReader
(1)创建字符输入流
new FileReader(file/String)
(2)read()每次读取单个字符,文件结束返回 -1
(3)read(char [ ] c)批量读取多个字符到数组中,返回读取到的字符数,到文件结束返回 -1
相关方法
new String(char[] c)将字符数组转换成字符串
new String(char[] c,int off,int len)将字符数组转换成字符串,off 为起始位置,len 作为结束位置
案例: 在控制台打印文本文件,包含汉字,字母
String Filepath = "e:\\note.text";
FileReader fileReader = new FileReader(Filepath);
int readlen = 0;
char[] r = new char[8];
//while 循环读取文件数据
while ((readlen = fileReader.read(r)) != -1) {
System.out.println(new String(r, 0, readlen));
}
fileReader.close();//文件关闭
}
1. 字符输出流-------FileWriter
(1)创建字符输出流
new FileWriter (file /String)//覆盖模式
new FileWriter (file /String,true)//追加模式
(2)
write(int)写入单个字符
write(char [ ] c)写入指定字符
write(char [ ] c ,int off, int len):,off 为起始位置,len 作为要写入的字符数
注:写入完毕,必须要关闭或刷新操作
案例: 写十句,“坚持即为胜利”,并保存在文件中
String Content = "坚持即为胜利";
char[] chars = Content.toCharArray();//转换字符数组,也可不转换
File file = new File("e:\\note.text");
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file,true);//追加写模式
for (int i = 0; i < 10; i++) {
fileWriter.write(chars);//循环写入
fileWriter.write("\n");//中间加入换行符
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileWriter.close();//关闭文件,否则就会写入失败
} catch (IOException e) {
e.printStackTrace();
}
}
二、节点流处理流
1. 节点流可以从一个特定的数据源,进行读写操作,例如,FileInputStream,FileOutputStream,字符输入输出流。
2. 处理流(包装流),就是对节点流进行包装,在节点流功能有限,进行扩展。不再局限于一个特定的数据源,例如 BufferedReader , BufferedWriter。.
1、字符处理流
(1). 字符输入处理流 BufferedReader
从字符输入流读取文本,缓冲字符,以提供字符,数组和行的高效读取。
new BufferedReader(Reader re)
方法摘要
(2). 字符输出处理流--BufferedWriter
将文本写入字符输出流,缓冲字符,以提供单个字符,数组和字符串的高效写入。
new BufferedWriter (Writer out),,对文件处理就传入FileWriter。
注意:写入完数据之后 必须将流关闭,或者刷新,否则保存不到数据。
方法摘要
案例:利用字符输入输出处理流,进行文本文件的拷贝
public static void main(String[] args) throws Exception {
BufferedReader bis = new BufferedReader(new FileReader("e:\\note.text"));
BufferedWriter bfw = new BufferedWriter(new FileWriter("e:\\note2.text",true));
String readCon;
while ((readCon = bis.readLine()) != null) {//循环读入一行
bfw.write(readCon);//写入
bfw.newLine();//加入一个空行
}
bis.close();
bfw.close();
}
三、字节处理流
1、字节输入流--BufferedInputStream
new BufferedInputStream (InputStream in)
只要是实现了InputStream接口,都可以加入,具体如下
添加 FileInputStream
方法摘要
2、字节输出处理流
BufferedOutputStream
该类实现缓冲输出流。 通过设置这样的输出流,应用程序可以向底层输出流写入字节,而不必为写入的每个字节导致底层系统的调用。
1. new BufferedOutputStream(OutputStream out)
方法摘要
案例:实现对一个文件中的图片/音频进行拷贝
public void Bufferedcopy () throws Exception{
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("e:\\FileCopy01.jpg"));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("e:\\Buffered.jpg"));
byte[] b = new byte[1024];
int readnums = 0;
while ((readnums = inputStream.read(b)) != -1) {
outputStream.write(b, 0, readnums);
}
inputStream.close();
outputStream.close();
}
}
四、对象处理流
可以对基本数据类型或者对象进行序列化操作和反序列化操作
1. 序列化就是(数据保存时,不仅要保存数据的值,还要保存数据的类型)
2. 反序列化就是在恢复数据时,恢复数据的值和类型
3. 如果实现对象进行序列化必须实现 Serializable (标记接口)。
1. ObjectOutputStream,可以对数据进行序列化操作
2. ObjectInputStream,可以对数据进行反序列化操作
练习,创建一个类,并对类进行序列化,保存在本地磁盘上,并利用ObjectInputStream,进行反序列化,读取文件
public class ObjectOut_ {
public static void main(String[] args) throws Exception {
Love love = new Love("至尊宝", 1500, 10000);
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("e:\\love.txt"));
outputStream.writeObject(love);
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("e:\\love.txt"));
System.out.println(objectInputStream.readObject());
objectInputStream.close();
outputStream.close();
}
}
class Love implements Serializable {//实现Serializable接口,才可
private String name;
private int age;
private int years;
public Love(String name, int age, int years) {
this.name = name;
this.age = age;
this.years = years;
}
@Override
public String toString() {
return "Love{" +
"name='" + name + '\'' +
", age=" + age +
", years=" + years +
'}';
}
}
对象处理流细节说明:
1. 读写的顺序要一致。
2. 要求实现序列化和反序列化的对象,要实现Serializable。
3. 加入private static final long serialVersionUID, 提高版本兼容性。
4. 序列化对象时,默认将里面所有的属性都进行序列化,除了static / transient (修饰的成员)
5. 序列化对象时,要求里面的属性的类型也要实现序列化接口。
6. 序列化具有可继承性,一个类实现了序列化,则它所有的子类也默认实现了序列化。
五、标椎输入/输出流
1. 标准输入流---System.in
编译类型是 Stream,运行类型是 BufferedInputStream,从键盘输入
2. 标准输出流--System.out
b编译类型是System , 运行类型是 PrintStream,将内容输出到显示器,System.setOut(Writer )
六、转换流 字节流----> 字符流
防止读数据时出现乱码,默认为UTF-8编码,如果不是,则字符流读取会出现乱码情况,这时候需要我们,设定编码类型,以防止出现乱码。
1. InputStreamReader
关系图
案例:读取gbk编码的文件内容
String filepath = "e:\\note.text";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
(new FileInputStream(filepath), "gbk"));
String Content = null;
while ((Content = bufferedReader.readLine()) != null) {
System.out.println(Content);
}
bufferedReader.close();
2. OutputStreamWriter
关系图
案例:向文件写入gbk编码的文件内容
String FilePath = "e:\\word.text";//写入文件的路径
OutputStreamWriter gbkFile = new OutputStreamWriter(new FileOutputStream(FilePath), "gbk");
BufferedWriter bufferedWriter = new BufferedWriter(gbkFile);
bufferedWriter.write("世界之大,我想去看看");//写入内容
bufferedWriter.close();
七、打印流(只有输出流)
1. 字节打印流 PrintStream
A
PrintStream
为另一个输出流添加了功能,即能够方便地打印各种数据值的表示。 还提供了另外两个功能。 与其他输出流不同,PrintStream
从不抛出IOException
; 相反,异常情况只是设置一个可以通过checkError
方法测试的内部标志。 可以选择一个PrintStream
,以便自动刷新; 这意味着flush
字节数组写入方法后自动调用,所述一个println
方法被调用时,或者一个新行字符或字节('\n'
)被写入。由印刷的所有字符
PrintStream
被转换成使用平台的默认字符编码字节。 在需要编写字符而不是字节的情况下,应使用PrintWriter
类。
将一句话打印到显示器中
PrintStream printStream = new PrintStream(System.out);
printStream.println("年后世界");
printStream.close();
讲一句话输出到文件中
PrintStream printStream = new PrintStream(System.out);
System.setOut(new PrintStream(FilePath));
printStream.write("年后世界".getBytes());
printStream.close();
字符打印流 PrintWriter---》用法大致相同
八、Properties集合配置文件
properties 常用方法
1. load 加载配置文件到properties对象中。
2. list ,将数据输出到指定设备。
3. getProperty(Key)获取键对应的值。
4. setProperty(key,value),设置键值对到properties对象中。有键则修改其值,没有则添加
5. store:将数据储存到配置文件中。
1. 读取文件
Properties properties = new Properties();//创建properties对象
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("src/mysql.properties"),"gbk");
properties.load(inputStreamReader);
//将数据加载到properties对象
properties.list(System.out);//输出
2. 加载到文件
public static void main(String[] args) throws IOException {
Properties properties = new Properties();//创建properties对象
properties.setProperty("uesrname","小李");
properties.setProperty("拜拜","再见");//comments 是注释,写入文件提示
properties.store(new FileWriter("src\\mysql.properties"),null);
}