文件基础
文件流
文件在程序中是以流的形式来操作的
Java程序(内存)—输入流—-》 文件(磁盘)—输出流—》Java程序(内存)
流 :数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
常用的文件操作
创建文件对象相关构造器和相关方法
new File(String pathn加粗样式ame) // 直接根据路径构建一个File对象
new File(File parent, String chile) // 根据父目录文件对象+子路径构建
new File(String parent, String child) // 根据父目录路径+子路径构建
// 方式一:new File(String pathname) 直接根据路径构建一个File对象
@Test
public void fileCrate01(){
String filePath = "E:\\Java\\Java学习笔记\\IO流\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件1创建成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// 方式二:new File(File parent, String chile) 根据父目录文件对象+子路径构建
@Test
public void fileCrate02(){
File parentFile = new File("E:\\Java\\Java学习笔记\\IO流\\");
String fileName = "news2.txt";
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件2创建成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// new File(String parent, String child) 根据父目录路径+子路径构建
@Test
public void fileCrate03(){
String parentPath = "E:\\Java\\Java学习笔记\\IO流\\";
String fileName = "news03.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("文件3创建成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
获取文件的相关信息
getName // 获取文件的名字
getAbsolutePath // 获取文件的绝对路径
getParent // 获取文件的父级目录
length // 获取文件的大小(文件中有多少字节)
exists // 是否存在这个文件
isFile // 是不是一个文件
isDirectory // 是不是一个目录
// 获取文件的信息
@Test
public void info(){
File file = new File("E:\\Java\\Java学习笔记\\IO流\\news1.txt");
// getName 获取文件的名字
System.out.println("文件名:" + file.getName());
// getAbsolutePath 获取文件的绝对路径
System.out.println("绝对路径:" + file.getAbsolutePath());
// getParent 获取文件的父级目录
System.out.println("父级目录:" + file.getParent());
// length 获取文件的大小(文件中有多少字节)
System.out.println("文件大小:" + file.length());
// exists 是否存在这个文件
System.out.println("是否存在:" + file.exists());
// isFile 是不是一个文件
System.out.println("是不是一个文件:" + file.isFile());
// isDirectory 是不是一个目录
System.out.println("是不是一个目录:" + file.isDirectory());
}
目录的操作和文件删除
mkdir // 创建一级目录
mkdirs // 创建多级目录
delete // 删除空目录或文件
// 判断文件E:\Java\Java学习笔记\IO流\news1.txt 是否存在,如存在就删除。如不存在,则创建
@Test
public void m1(){
String filePath = "E:\\Java\\Java学习笔记\\IO流\\news1.txt";
File file = new File(filePath);
if(file.exists()) {
if(file.delete())
System.out.println("news1.txt 被删除!");
else
System.out.println("文件删除失败!");
}else{
try {
file.createNewFile();
System.out.println("news1.txt 被创建!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
// 判断目录E:\Java\Java学习笔记\IO流\Dir 是否存在,如存在就删除。如不存在,则创建
@Test
public void m2() {
String dirPath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\AA";
File dir = new File(dirPath);
if (dir.exists()) {
if (dir.delete())
System.out.println(dirPath + " 目录被删除!");
else
System.out.println(dirPath + "目录删除失败!");
} else {
System.out.println("目录不存在,正在创建...");
if(dir.mkdirs()){
System.out.println(dirPath + " 目录创建成功!");
}else
System.out.println("目录创建失败!");
}
}
Java IO流原理及流的分类
流原理
- I/O 技术是非常实用的技术,用于处理数据传输。 如读/写文件,网络通讯等
- Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行
- java.io 包下提了各种流类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
流的分类
- 按操作数据单位不同分为:字节流(8 bit),字符流(按字符)
- 按数据流的流向不同分为:输入流、输出流
- 按流的角色不同分为:节点流,处理流/包装流
(抽象基类) | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
IO流常用类
IO字节节点流
InputStream 字节输入流
InputStream 抽象类是所有类字节输入流的超类
InputStream 常用子类
- FileInputStream :文件输入流
- BufferedInputStream : 缓冲字节输入流
- ObjectInputStream :对象字节输入流
案例 :读取文件
// 单个字节的读取,效率比较低
public void readFile01(){
int readData = 0;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
// 从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
// 如果返回-1,表示读取完毕
while((readData = fileInputStream.read()) != -1){
System.out.print((char) readData); // 转成char显示
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally { // 关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
// 使用read(byte[] b) 读取文件,提高效率
public void readFile02(){
// 字节数组
byte[] buf = new byte[8]; // 一次读取8个字节
int readLen = 0;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
// 如果返回-1,表示读取完毕
while((readLen = fileInputStream.read(buf)) != -1){
System.out.print(new String(buf,0, readLen)); // 转成字符串显示
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally { // 关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
OutputStream 字节输出流
OutputStream 常用子类
FileOutputStream
案例:写入文件
/**+
*要求:在 E:\Java\Java学习笔记\IO流\Dir\a.txt文件中
* 写入: hello,world
* [如果文件不存在,则创建文件](前提是目录已存在)
*/
@Test
public void writeFile() {
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\a.txt";
FileOutputStream fileOutputStream = null;
try {
// new FileOutputStream(filePath); 这样的创建方式,当写入内容时,会覆盖原来的内容
// new FileOutputStream(filePath,true); 这样的创建方式,写入内容时会追加到文件内容的最后
fileOutputStream = new FileOutputStream(filePath);
String str = "hello,world";
// fileOutputStream.write(str.getBytes());
// write(byte[] b, int off, int len)
fileOutputStream.write(str.getBytes(), 0, str.length());
System.out.println("写入成功");
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
综合案例:完成图片拷贝
public static void main(String[] args) {
// 完成文件拷贝 复制图片 E:\Java\Java学习笔记\IO流\Dir\lufei.jpg
// 1. 创建文件的输入流,读取图片
// 2.创建文件的输入流,复制图片写入
FileInputStream fileInputStream = null; // 文件输入流对象
FileOutputStream fileOutputStream = null; // 文件输出流对象
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\";
try {
byte[] buf = new byte[8]; // 字节数组:一次读取8个字节
int readLen = 0; // 表示读取到的长度
// 创建 输入流 对象
fileInputStream = new FileInputStream(filePath + "lufei.jpg");
// 创建 输出流对象 (追加)
fileOutputStream = new FileOutputStream(filePath + "lufei2.jpg", true);
while((readLen = fileInputStream.read(buf)) != -1){
fileOutputStream.write(buf, 0, readLen);
}
System.out.println("图片复制成功");
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
if(fileInputStream != null)
fileInputStream.close();
if(fileOutputStream != null)
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
IO字符节点流
FileReader 字符输入流
相关方法
1. new FileReader(File/String)
2. read() // 每次读取单个字符,返回该字符,如果到文件末尾返回 -1
3. read(char[]) // 批量读取多个字符到数组。返回读取到的字符数,如果到文件末尾返回 -1
相关API
- new String(char[]) // 将char[] 转换为 String
- new String(char[], off, len) // 将char[]指定部分转换成String
案例
public static void main(String[] args) {
FileReader fileReader = null;
try {
char[] chs = new char[8];
int readLen = 0;
fileReader = new FileReader("E:\\Java\\Java学习笔记\\IO流\\Dir\\story.txt");
while ((readLen = fileReader.read(chs)) != -1) {
System.out.print(new String(chs, 0, readLen));
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (fileReader != null)
fileReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
FileWriter 字符输出流
常用方法
- new FileWriter(File / String) // 覆盖模式,相当于流的指针在首端
- new FileWriter(File / String, true) // 追加模式,相当于流的指针在尾端
- write(int) // 写入单个字符
- write(char[]) // 写入指定数组
- write(char[], off, len) // 写入指定数组的指定部分
- write(String) // 写入整个字符串
- write(String, off, len) // 写入指定字符串的指定部分
相关API
- String类 toCharArray: 将String转换成char[]
注意:FileWriter使用后,必须要关闭(close)或者刷新(flush),否则将写入不到指定的问价
案例
public static void main(String[] args) {
String str = "hello world!\n你好世界";
FileWriter fileWriter = null;
try {
//fileWriter = new FileWriter(filePath,true); 表示追加
fileWriter = new FileWriter("E:\\Java\\Java学习笔记\\IO流\\Dir\\FileWriterTest.txt");
fileWriter.write(str);
System.out.println("写入成功");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(fileWriter != null)
fileWriter.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
节点流和处理流
基本介绍
1. 节点流可以从一个特定的数据源(文件/字符串..)**读写数据**,如FIleReader、FileWriter
2. 处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如BufferedWriter
节点流和处理流的区别与联系
- 节点流是底层流/低级流,直接跟数据源相接
- 处理流包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出
- 处理流对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连
处理流功能主要体现
- 性能的提高:主要以增加缓冲的方式来提高输入输出的效率、
- 操作的便捷:处理六可能提供了一系列便捷的方法,来一次输入输出大批量的数据,使用就是的。我们他的这个更加灵活方便
常用处理流
字符处理流
BufferedReader与BufferedWriter是按照字符来读取数据的,不要操作二进制文件,否则可能会造成文件损坏
关闭处理流时,只需要关闭外层流即可
BufferedReader 读取案例
public static void main(String[] args) {
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\story.txt";
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line; // 按行读取
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {// 关闭流
try {
if(bufferedReader != null)
bufferedReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
BufferedWriter 写入案例
public static void main(String[] args) {
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\a.txt";
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(filePath));
String str = "hello LeoBoy";
String str2 = "hello world";
bufferedWriter.write(str);
bufferedWriter.newLine(); // 插入系统相关的换行符
bufferedWriter.write(str2);
} catch (IOException e) {
throw new RuntimeException(e);
} finally { // 关闭流
try {
if(bufferedWriter != null)
bufferedWriter.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
综合案例:文件拷贝
public static void main(String[] args) {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\";
String fileName = "story";
try {
bufferedReader = new BufferedReader(new FileReader(filePath + fileName + ".txt"));
bufferedWriter = new BufferedWriter(new FileWriter(filePath + fileName + "_copy.txt"));
// 按行读取文件
String line;
while ((line = bufferedReader.readLine()) != null){
bufferedWriter.write(line);
bufferedWriter.newLine();
}
System.out.println("文件Copy成功!");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (bufferedReader != null)
bufferedReader.close();
if (bufferedWriter != null)
bufferedWriter.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
字节处理流
BufferedInputStream与BufferedOutputStream 是字节流,适合处理二进制文件
BufferedInputStream
在创建BufferedInputStream时,会创建一个内部缓冲区数组
BufferedOutputStream
是实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统
综合案例:Copy 图片
public static void main(String[] args) {
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\";
String fileName = "lufei";
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath+ fileName + ".jpg"));
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath + fileName +"_copy.jpg"));
byte[] bys = new byte[8];
int readLen = 0;
while((readLen = bufferedInputStream.read(bys)) != -1){
bufferedOutputStream.write(bys, 0, readLen);
}
System.out.println("图片Copy成功!");
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
if(bufferedInputStream != null)
bufferedInputStream.close();
if(bufferedOutputStream != null)
bufferedOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
对象处理流
ObjectInputStream / ObjectOutputStream
看一个需求
-
将int num = 100这个 int数据保存到文件中,注意不是100数字,而是int 100,并且,能够 从文件中直接恢复int 100
-
将Dog=new Dog(“小黄”,3)这个Dog对象保存到文件中,并且能够从文件恢复.
-
上面的要求,就是能够将基本数据类型或者对象进行序列化和反序列化操作
序列化和反序列化
1.序列化就是在保存数据时,保存数据的值和数据类型
2.反序列化就是在恢复数据时,恢复数据的值和数据类型
3.需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:
Serializable //这是一个标记接口,主要做声明,没有方法
Externalizable
ObjectOutputStream
public class ObjectOutputStream_ {
// 使用ObjectOutputStream序列化一个基本数据类型和一个Dog对象
// 并保存到 E:\Java\Java学习笔记\IO流\Dir\Data.dat
public static void main(String[] args) {
// 保存后的数据不是一个纯文本,而是一个对象数据(值+数据)
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\Data.dat";
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
objectOutputStream.write(100);
objectOutputStream.writeChar('a');
objectOutputStream.writeDouble(1.1);
objectOutputStream.writeBoolean(true);
objectOutputStream.writeUTF("小刘同学");
// 保存一个Dog对象
objectOutputStream.writeObject(new Dog("大黄", 3));
System.out.println("序列化保存成功!");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (objectOutputStream != null)
objectOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
class Dog implements Serializable {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
ObjectInputStream
public class ObjectInputStream_ {
// 使用ObjectInputStream读取data.dat并反序列化
public static void main(String[] args) {
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\Data.dat";
// 1. 创建流对象
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(filePath));
// 2. 读取,注意顺序(不按顺序会报异常)
System.out.println(objectInputStream.readInt());
System.out.println(objectInputStream.readChar());
System.out.println(objectInputStream.readDouble());
System.out.println(objectInputStream.readBoolean());
System.out.println(objectInputStream.readUTF());
System.out.println(objectInputStream.readObject());
System.out.println("反序列化读取成功!");
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} finally {
try {
if(objectInputStream != null)
objectInputStream.close();
}catch (IOException e){
throw new RuntimeException(e);
}
}
}
}
注意事项和相关细节
1)读写顺序要一致
2)要求实现序列化或反序列化对象,需要实现 Serializable
3)序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
// SerialVersionUID序列化的版本号可以提高兼容性
private static final long SerialVersionUID = 1L;
4)序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员(可理解为不保存)
5)序列化对象时,要求里面属性的类型也需要实现序列化接口
6)序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化
标准输入输出流
System.in 标准输入 类型:InputStream 默认设备:键盘
System.out 标准输出 类型:PrintStream 默认设备:显示器
转换流
作用:把一种字节流转换成字符流
介绍
- InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流)
- OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)
- 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
- 可以在使用时指定编码格式(比如utf-8, gbk , gb2312, ISO8859-1等)
InputStreamReader
案例:
用InputStreamReader解决乱码问题
public static void main(String[] args) {
// 将字节流FileInputStream包装成字符流InputStreamReader
// 对文件进行读取(按照utf-8/gbk格式)
// 进而在包装成BufferedReader
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\a.txt";
BufferedReader bufferedReader = null;
try {
// 1. 创建InputStreamReader对象
bufferedReader = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), "gbk"));
String line; // 2. 按行读取
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally { // 3.关闭
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
OutputStreamWriter
案例:
OutputStreamWriter解决乱码问题
public static void main(String[] args) throws IOException {
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\a.txt";
// 将字节流FileOutputStream 转换成字符流 OutputStreamWriter
// 将 字符流 转换成 BufferedWriter
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "gbk"));
// 2.写入文件
bufferedWriter.write("小刘同学");
bufferedWriter.newLine();
// 3.关闭文件
bufferedWriter.close();
}
Properties类
此类方便读取配置文件
配置文件的格式:
键=值
键=值
键值对不需要空格,值不需要用引号引起来,默认是String类型
基本介绍
- load: 加载配置文件的键值对到Properties对象
- list:将数据显示到指定设备
- getProperty(key):根据键获取值
- setProperty(key,value):设置键值对到Properties对象
- store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件.
如果含有中文,会存储为unicode码
http://tool.chinaz.com/tools/unicode.aspx unicode码查询工具
案例
public static void main(String[] args) {
String filePath = "E:\\Java\\Java学习笔记\\IO流\\Dir\\mysql.properties";
// 使用 Properties 读取配置文件
// 1. 创建Properties对象
Properties properties = new Properties();
try {
// 2. 加载配置文件中的键值对
properties.load(new FileReader(filePath));
// 3.把键值对显示到控制台
properties.list(System.out);
// 4.根据key 获取对应的值
String dbName = properties.getProperty("dbName");
String userName = properties.getProperty("userName");
System.out.println("dbName=" + dbName);
System.out.println("userName=" + userName);
System.out.println("=========================");
// 1. 根据Properties 类修改/添加 键值对
properties.setProperty("ip","127.0.0.1");
properties.setProperty("dbName", "NewDbName");
// 2. 存储到文件中
properties.store(new FileWriter(filePath), null); // comments 注释/注解
// 把键值对显示到控制台
properties.load(new FileReader(filePath));
properties.list(System.out);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println();
}