java IO专题
文件流
文件在程序中是以流的形式来操作的
流:数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
常见的文件操作
创建文件对象相关构造器和方法
相关方法
1、new File(String pathname) //根据路径构建一个file对象
2、new File(File parent,String child) //根据父目录 + 子目录构建
3、new File(String parent,String child) //根据父目录 + 子路径构建
createNewFile 创建新文件
// 方式一: new File(String pathname) //根据路径构建一个file对象
@Test
public void create01(){
String filePath = "e:\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式二: new File(File parent,String child) //根据父目录 + 子目录构建
@Test
public void create02(){
File parentFile = new File("e:\\");
String fileName = "news2.txt";
//这里的 file 对象,在java程序中,只是一个对象
//只有执行 createNewFile 方法,才会被真正的在磁盘中创建改文件
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式三: new File(String parent,String child) //根据父目录 + 子路径构建
@Test
public void create(){
File parentPath = new File("e:/");
String fileName = "news3.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
获取文件的相关信息
常用的方法
getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
//获取文件的信息
@Test
public void info(){
//先创建文件
File file = new File("e:\\news1.txt");
//调用相应的方法,得到对应的信息
System.out.println("文件的名字————"+file.getName());
System.out.println("文件的绝对路径————"+file.getAbsolutePath());
System.out.println("文件父极目录————"+file.getParent());
System.out.println("文件大小(字节)————"+file.length());
System.out.println("文件是否存在————"+file.exists());
System.out.println("是不是一个文件————"+file.isFile());
System.out.println("是不是一个目录————"+file.isDirectory());
}
目录的操作和文件的删除
mkdir 创建一级目录、mkdirs创建多级目录、delete删除空目录或文件
案例
//判断该 e:\\news1.txt 文件是否存在,存在就删除,否则就提示不存在
@Test
public void m1(){
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("该文件不存在~~~");
}
}
//判断该 e:\\demo02 目录是否存在,存在就删除,否则就提示不存在
@Test
public void m2(){
String filePath = "e:\\demo02";
File file = new File(filePath);
//这里我们需要体会到,在java编程中,空目录也被当成文件
if (file.exists()){
if (file.delete()) {
System.out.println(filePath + "~~~~~~删除成功!");
}else {
System.out.println(filePath + "~~~~~~删除失败!");
}
}else {
System.out.println("该目录不存在~~~");
}
}
//判断该 e:\\demo02\\a\\b\\c 目录是否存在,存在就提示文件已存在,否则就创建
@Test
public void m3(){
String directoryPath = "e:\\demo02\\a\\b\\c";
File file = new File(directoryPath);
if (file.exists()){
System.out.println(directoryPath + "~~~~文件已存在");
}else {
if (file.mkdirs()) {//创建一级目录使用mkdir()方法,多级加 s
System.out.println(directoryPath + "~~~~~~创建成功!");
}else {
System.out.println(directoryPath + "~~~~~~创建失败!");
}
}
}
IO流原理及流的分类
Java IO流原理
- I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输,如读/写文件,网络通讯等。
- Java程序中,对于数据的输入/输出操作以 “流(stream)” 的方式进行。
- java.io下提供了各种 ”流” 类和接口,用以获取不同类的数据,并通过对象输入或输出数据。
- 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
- 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中。
流的分类
- 按操作数据单位不同分为:字节流(8 bit)二进制文件,字符流(按字节)文本文件
- 按数据流的流向不同分为:输入流,输出流
- 按流的角色的不同分为:节点流,处理流/包装流
(抽象基类) | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。
由这四个类派生出来的子类名称都是以其父类名作为子类后缀。
IO流体系图-常用的类
- IO流体系图
- 文件 VS 流
InputStream:字节输入流
- InputStream抽象类是所有类字节输入流的超类
- InpuStream 常用的子类
- FileInputStream:文件输入流
- BufferedInputStream:缓冲字节输入流
- ObjectInputStream:对象字节输入流
FileInputStream
关系图
案例
package com.langchao.inputstream;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 演示FileInputStream的使用(字节输入流 文件——>程序)
*/
public class FileInputStream_ {
/**
* 演示文件读取
* 单个字节读取,效率比较低
*/
@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 (Exception 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[15];//一次读取8个字节
int readLen = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取文件
fileInputStream = new FileInputStream(filePath);
//从该输入流兑取最多 b.length 字节的数据到字节数组。此方法将阻塞,直到某些输入可用
//如果返回 -1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
System.out.print(new String(buf,0,readLen));//显示
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileOutputStream
关系图
实例
package com.langchao.outputstream_;
import org.junit.Test;
import java.io.FileOutputStream;
import java.io.IOException;
public class OutputStream_ {
/**
* 演示使用 FileOutputStream 将数据写到文件中
* 如果该文件不存在,则创建文件
*/
@Test
public void writeFile(){
//创建 FileOutputStream 对象
String filePath = "e:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
//注意!!!老韩说明
//1、new FileOutputStream(filePath); 创建方式,当写入内容时,会覆盖原来的内容
//2、new FileOutputStream(filePath,true);创建方式,当写入内容时,会追加到原内容后面
fileOutputStream = new FileOutputStream(filePath,true);
//写入一个字节
//fileOutputStream.write('H');
//写入字符串 .getBytes()字符串转换成一个字节数组
//fileOutputStream.write("hello,world".getBytes());
String str = "~nihao,xiaohuozi";
/*
write(byte b[], int off, int len)
将 len 字节从位于偏移量 off的指定的字节数组写入此文件输出流
*/
fileOutputStream.write(str.getBytes(),0,6);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件拷贝
实例
要求:变成完成图片/音乐 的拷贝
public class FileCopy {
public static void main(String[] args) {
//完成 文件拷贝,将 e:\\1.png 拷贝 d:
//思路分析
//1.创建文件的输入流,将文件读入到程序
//2.创建文件的输出流,将读取的文件数据,写入到指定的文件。
String srcFilePath = "e:\\1.png";
String destFilePath = "e:\\anihao.png";
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("文件拷贝成功~~~");
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭输入流和输出流,释放资源
try {
if (fileInputStream != null){
fileInputStream.close();
}
if (fileOutputStream != null){
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileReader 和 FileWriter 介绍
FileReader 和 FileWriter 是字符流,即按照字符来操作io
FileReader相关方法
1、new FileReader(File/String)
2、read:每次读取单个字符,返回该字符,如果到文件末尾返回 -1
3、read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回 -1相关的API
相关API:
1、new String(char[]):将char[]转换成String
2、new String(char[],off,len):将char[]的指定部分转换成String
关系图
实例
public class FileReader_ {
/**
* 字符数组读取文件
*/
@Test
public void 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();
}
}
}
/**
* 单个字符读取文件
*/
@Test
public void readFile01(){
String filePath = "e:\\story.txt";
FileReader fileReader = null;
int data = 0;
//1、创建 FileReader 对象
try {
fileReader = new FileReader(filePath);
//循环读取 使用read,单个字节数读取
while ((data = (fileReader.read())) != -1){
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileReader != null){
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
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):写入字符串的指定部分
相关API:
String类:toCharArray:将String转换成char[]
注意:
FileWriter使用后,必须要关闭(colse)或刷新(flush),否则写入不到指定的文件!
关系图
public class 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,true);
fileWriter.write('H');
fileWriter.write(chars);
fileWriter.write("韩老师牛批".toCharArray(),0,3);
fileWriter.write("风雨之后,定见彩虹",1,3);
//数据量大的情况下,可以使用循环操作。
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//对应FileWriter,一定要关闭流或者刷新流,否则数据没有存入指定文件
//并没有走writeBytes()方法,就没有进行内容存入的操作
//关闭文件流,等同于flush+关闭
//fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("程序结束~~~");
}
}
节点流和处理流
1、基本介绍
1、节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter[源码]
2、处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也跟更加的灵活,如BufferedReader、BuffredWriter[源码]
2、节点流和处理流一览图
public class BufferedReader extends Reader {
private Reader in;
...
注意:
BufferedReader类中,有属性Reader,即可以封装一个节点流,该节点流是可以任意的,只要是Reader的子类
3、节点流和处理流的区别和联系
- 节点流是底层流/低级流,直接跟数据源相接
- 处理流包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。[源码理解]
- 处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相联[模拟修饰器设计模式
处理流的功能主要体现在以下两个方面:
- 性能的提高:主要以增加缓冲的方式来提高输入和输出的效率。
- 操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便
4、处理流-BufferedReader 和 BufferedWrider
注意:BufferedReader和BufferedWrider
属于字符流,是按照字符来读取数据的,关闭时,只需要关闭外层流即可。【因为底层会调用的处理流传入的字节流的close方法】
(1)BufferedReader读取文本文件
package com.langchao.reader_;
import java.io.BufferedReader;
import java.io.FileReader;
public class BufferedReader_ {
public static void main(String[] args) throws Exception {
String filePath = "e:\\a.java";
//创建 BufferedReader
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
//读取
String line;//按行读取,效率高
//说明
//1.bufferedReader.readLine() 是按行读取文件
//2.当返回null时,表示文件读取完毕
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
//关闭流,这里注意,只需要关闭 BufferedReader,因为底层会自动的去关闭 节点流
//FileReader
bufferedReader.close();
}
}
(2)BufferedWriter写入文本文件
package com.langchao.writer_;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriter_ {
public static void main(String[] args) throws IOException {
String filePath = "e:\\ok.txt";
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
bufferedWriter.write("hello,韩顺平教育");
bufferedWriter.newLine();//插入一个和系统相关的换行
bufferedWriter.write("hello2,韩顺平教育");
bufferedWriter.newLine();
bufferedWriter.write("hello3,韩顺平教育");
//说明:关闭外层流即可,传入的 new FileWriter(filePath),会在底层关闭
bufferedWriter.close();
}
}
(3)BufferedReader 和 BufferedWrider 完成 文本文件拷贝
package com.langchao.writer_;
import java.io.*;
public class BufferedCopy_ {
public static void main(String[] args) {
//老韩说明
//1、BufferedReader 和 BufferedWriter 是按字符操作的
//2、不要去操作 二进制文件[声音,视频,doc,pdf]。可能造成文件损坏
String srcFilePath = "e:\\a.java";
String destFilePath = "e:\\a2.java";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
try {
br = new BufferedReader(new FileReader(srcFilePath));
bw = new BufferedWriter(new FileWriter(destFilePath));
//说明readLine 读取一行内容,但是没有换行
while ((line = br.readLine()) != null) {
//读取一行,就写入
bw.write(line);
//插入一个换行
bw.newLine();
}
System.out.println("拷贝完毕~~~");
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭流
try {
if (br != null || bw != null){
br.close();
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5、处理流-BufferedInputStream 和 BufferedOutputStream
BufferedInputStream是字节流,在创建BufferedInputStream时,会创建一个内部缓冲数组。
BufferedInputStream 关系图
BufferedInputStream是字节流,在创建BufferedInputStream时,会创建内部缓冲区数组。
BufferedOutputStream 关系图
BufferedOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统。
BufferedInputStream 和 BufferedOutputStream —应用实例
package com.langchao.outputstream_;
import java.io.*;
/**
* 演示 BufferedInputStream 和 BufferedOutputStream 的使用
* 使用他们,可以完成二进制文件的拷贝,也可以完成操作文本文件的拷贝
*/
public class BufferedCopy02 {
public static void main(String[] args) {
//此处拷贝的是视频文件
String srcFilePath = "e:\\你好.mp4";
String destFilePath = "e:\\呵呵哒.mp4";
//创建 BufferedInputStream 和 BufferedOutputStream 对象
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(srcFilePath));
bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
//循环读取文件,并写入到 destFilePath
byte[] buff = new byte[1024];
int readLen = 0;
//当返回 -1 时,就表示文件读取完毕
while ((readLen = bis.read(buff)) != -1){
bos.write(buff,0,readLen);
}
System.out.println("文件拷贝完毕~~~");
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭流,关闭外层的处理流即可,底层会去关闭节点流
try {
if (bis != null || bos != null){
bis.close();
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
6、对象流— ObjectInputStream和ObjectOutputStream
序列化和反序列化
- 序列化就是在保存数据时,保存数据的值和数据类型
- 反序列化就是在恢复数据的时,恢复数据的值和数据类型
- 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个是可序列化的,该类必须实现如下两个接口之一:
- Serializable //这是一个标记接口
- Externalizable //该接口继承了Serializable ,该接口有方法要实现,一般使用 Serializable接口,
1、ObjectOutputStream
关系图
实例
使用ObjectOutputStream 序列化 基本数据类型和 一个Dog对象(name,age),并保存到data.dat文件中。
ObjectOutputStream_.java
package com.langchao.outputstream_;
import java.io.*;
/**
* 演示 ObjectOutputStream 的使用,完成数据实例化
*/
public class ObjectOutputStream_ {
public static void main(String[] args) throws IOException {
//序列化后,保存的文件格式,不是纯文本,而是按照他的格式来保存
String filePath = "e:\\data.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到 e:\data.dat
oos.writeInt(100);// int -> Integer(实现了 Serializable)
oos.writeBoolean(true);// boolean -> Boolean(实现了 Serializable)
oos.writeChar('a');// char -> Character(实现了 Serializable)
oos.writeDouble(6.6);// double -> Double(实现了 Serializable)
oos.writeUTF("韩顺平教育");//String
//保存一个dog对象
oos.writeObject(new Dog("旺财",10));
oos.close();
System.out.println("数据保存完毕(序列化形式)");
}
}
//如果需要序列化某个类的对象,必须实现接口 Serializable或者Externalizable
class Dog implements Serializable{
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
2、ObjectInputStream
关系图
实例
package com.langchao.inputstream_;
import com.langchao.outputstream_.Dog;
import java.io.*;
public class ObjectInputStream_ {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//指定反序列化的文件
String filePath = "e:\\data.dat";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
//读取
//老师解读
//1.读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
System.out.println(ois.readInt());
System.out.println(ois.readBoolean());
System.out.println(ois.readChar());
System.out.println(ois.readDouble());
System.out.println(ois.readUTF());
Object dog = ois.readObject();
System.out.println("运行类型=" + dog.getClass());
System.out.println("dog信息=" + dog);// 底层 Object -> Dog
//这里是特别重要的细节:
//1、如果我们希望调用Dog的方法,需要向下转型
//2、需要我们将Dog类的定义,放在 public到可以引用的位置
Dog dog2 = (Dog)dog;
System.out.println(dog2.getName());//旺财
//关闭外层流即可,底层自动会关闭干活的字节流 FileInputStream
ois.close();
}
}
注意事项和细节说明
- 读写顺序要一致。
- 要求实现序列化或反序列化对象,需要 实现 Serializable。
- 序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性。
- 序列化对象时,默认将里面所有属性都进行序列化,但是处理static或transient修饰的成员。
- 序列化对象时,要求里面属性的类型也需要实现序列化接口。
- 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化。
具体看P22集,这里代码不过多展示了
private String name;
private int age;
//序列化对象时,默认将里面所有属性都进行序列化,但是处理static或transient修饰的成员。
private static String nation;
private transient String color;
//序列化对象时,要求里面属性的类型也需要实现序列化接口。
private Master master = new Master();
//serialVersionUID 序列化的版本号,可以提高兼容性
private static final long serialVersionUID = 1L;
标准输入流和输出流
介绍
类型 默认设备
System.in标准输入 InputStream 键盘
System.out标准输出 PrintStream 显示器
案例
package com.langchao.standard;
import java.util.Scanner;
public class InputAndOutput {
public static void main(String[] args) {
//System 类的 public final static InputStream in = null;
//System.in 编译类型 InputStream
//System.in 运行类型 BufferedInputStream
//表示的是标准输入 键盘
System.out.println(System.in.getClass());
//老韩解读
//1、public final static PrintStream out = null;
//2、编译类型 PrintStream
//3、运行类型 PrintStream
//4、表示标准输出 显示器
System.out.println(System.out.getClass());
System.out.println("hello,韩顺平教育~");
Scanner scanner = new Scanner(System.in);
System.out.print("输入内容:");
String next = scanner.next();
System.out.println("next=" + next);
}
}
转换流—InputStreamReader和OutputStreamWriter
介绍
1、InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成(转换)Reader(字符流)
2、OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装后才能Writer(字符流)
3、当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
4、可以在使用时指定编码格式(比如utf-8,gbk,gb2312,ISO8859-1等)
InputStreamReader
关系图
案例
package com.langchao.transformation;
import java.io.*;
/**
* 演示使用 InputStreamReader 转换流解决中文乱码问题
* 将字节流 FileInputStream 转成字符流 InputStreamReader,指定编码 gbk/utf-8
*/
public class InputStreamReader_ {
public static void main(String[] args) throws IOException {
String filePath = "e:\\a.txt";
//解读
//1.把 FileInputStream转换成 InputStreamReader
//2.指定编码 gbk
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//3.把 InputStreamReader 传入 BufferedReader
//BufferedReader br = new BufferedReader(isr);
//把 2和3 合在一起
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));
//4.读取
String s = br.readLine();
System.out.println("读取内容:" + s);
//5.关闭外层流
br.close();
}
}
OutputStreamWriter
关系图
案例
package com.langchao.reader_;
import java.io.*;
/**
* 演示 OutputStreamWriter 使用
* 把 FileOutputStream 字节流,转成字符流 OutputStreamWriter
* 指定处理的编码 gbk/utf-8/utf8
*/
public class OutputStreamWriter_ {
public static void main(String[] args) throws IOException {
String filePath = "e:\\hsp.txt";
String charSet = "gbk";
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
osw.write("hi,韩顺平教育");
osw.close();
System.out.println("按照 "+ charSet + " 保存文件成功~~~");
}
}
打印流-PrintStream 和 PrintWriter
PrintStream 字符打印流
关系图
案例
package com.langchao.printstream;
import java.io.IOException;
import java.io.PrintStream;
/**
* 演示PrintStream (字符流/输出流)
*/
public class PrintStream_ {
public static void main(String[] args) throws IOException {
PrintStream out = System.out;
//在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
/*
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
*/
out.print("john,hello");
//因为print底层使用的是write,所以我们可以直接调用write进行打印/输出
out.write("韩顺平,你好".getBytes());
out.close();
//我们可以去修改打印流输出的位置/设备
//1.输出修改到 e:\f1.txt
//2.hello , 韩顺平教育~~ 就会输出到 e:\f1.txt
/*
public static void setOut(PrintStream out) {
checkIO();
setOut0(out);//native方法,修改了out
}
*/
System.setOut(new PrintStream("e:\\f1.txt"));
System.out.println("hello , 韩顺平教育~~");
}
}
PrintWriter 字节打印流
关系图
案例
package com.langchao.printstream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
*演示 PrintWriter 的使用
*/
public class PrintWriter_ {
public static void main(String[] args) throws IOException {
//PrintWriter printWriter = new PrintWriter(System.out);
PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
printWriter.print("h1,北京你好~~~");
printWriter.close();//flush + 关闭流,才会将数据写入到文件。。。
}
}
Properties类
一、基本介绍
1)专门用于读取配置文件的集合类
配置文件的格式
键=值
2)注意:键值不需要有空格,值不需要用引导一起来。默认类型是String
3)Properties的常见方法
- load:加载配置文件的键值对到properties对象
- list:将数据显示到指定设备
- getProperty(key):根据键获取值
- setProperties(key,value):设置键值对到Properties对象
- store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码
package com.langchao.properties_;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Properties01 {
public static void main(String[] args) throws IOException {
//读取mysql.properties 文件,并得到ip,user 和 pwd
BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
String line = "";
while ((line = br.readLine()) != null){//循环读取
String[] split = line.split("=");
System.out.println(split[0] + "值是: " + split[1]);
}
br.close();
}
}
package com.langchao.properties_;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class Properties02 {
public static void main(String[] args) throws IOException {
//使用 Properties 类来读取mysql.properties 文件
//1.创建Properties 对象
Properties properties = new Properties();
//2.加载指定配置文件
properties.load(new FileReader("src\\mysql.properties"));
//3.把k-v显示控制台
properties.list(System.out);
//2.根据key 获取对应的值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println("用户名是---"+user);
System.out.println("用户名是---"+pwd);
}
}
package com.langchao.properties_;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Properties03 {
public static void main(String[] args) throws IOException {
//使用 Properties 类来创建 配置文件,修改配置文件内容
//创建
//1.如果该文件没有key,就是创建
//2.如果该文件有key,就是修改
Properties properties = new Properties();
properties.setProperty("charset","utf8");
properties.setProperty("user","汤姆");//注意保存时,是中文的 unicode码值
properties.setProperty("pwd","abc111");
//将k-v 存储文件中即可
properties.store(new FileOutputStream("src\\mysql2.properties"),null);
System.out.println("保存配置文件成功~~~");
}
}
作业
Homework01
package com.langchao.work;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* (1)在判断e盘下是否有文件夹mytemp,如果么有就创建mytemp
* (2)在e:\\mytemp目录下,创建hello.txt
* (3)如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了
* (4)并且在hello.txt文件中,写入 hello,world~~
*/
public class Homework01 {
public static void main(String[] args) throws IOException {
String directoryPath = "e:\\mytemp";
File file = new File(directoryPath);
if (!file.exists()) {
//创建
if (!file.mkdirs()) {
System.out.println("创建 " + directoryPath + " 目录成功~~");
} else {
System.out.println("创建 " + directoryPath + " 目录失败~~");
}
}
String filePath = directoryPath + "\\hello.txt";
file = new File(filePath);
if (!file.exists()){
//创建文件
if (file.createNewFile()){
System.out.println(filePath + "创建成功~~~");
//如果文件存在,我们就使用BufferWriter 字符输入流写入文件
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write("hello,world~~~韩顺平教育");
bw.close();
}else{
System.out.println(filePath + "创建失败~~~");
}
}else {
//如果文件已经存在,则提示已经存在
System.out.println(filePath+"已经存在~不再重复创建~~");
}
}
}
Homework02
package com.langchao.work;
import java.io.*;
public class Homework02 {
public static void main(String[] args) {
/**
* 要求:使用 BufferedReader 读取一个文本文件,为每行加上行号
* 再连同内容一并输出到屏幕
*/
String filePath = "e:\\a.txt";
BufferedReader br = null;
String line = "";
int lineNum = 0;
try {
//br = new BufferedReader(new FileReader(filePath));
br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));
while ((line = br.readLine())!=null){
System.out.println(++lineNum + line);//循环读取
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Homework03
package com.langchao.work;
import org.junit.Test;
import java.io.*;
import java.util.Properties;
/**
* (1)要编写一个dog。properties name=tom age=5 color=red
* (2)编写Dog 类(name,age,color) 创建一个dog对象,读取dog.properties 用相应
* (3)将创建的Dog 对象,序列化到 文件 dog.dat 文件
*/
public class Homework03 {
public static void main(String[] args) throws IOException {
String filePath = "src\\dog.properties";
Properties properties = new Properties();
properties.load(new FileReader(filePath));
String name = properties.get("name")+"";//Object -> String
int age = Integer.parseInt(properties.get("age")+"");// Object -> int
String color = properties.get("color")+"";//Object -> String
Dog dog = new Dog(name, age, color);
System.out.println("====dog对象的信息====");
System.out.println(dog);
//将创建的Dog对象,序列化到 dog.txt 文件
String serFilePath = "e:\\dog.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
oos.writeObject(dog);
//关闭流
oos.close();
System.out.println("dog对象,序列化完成~~~");
}
//再编写一个方法,反序列化dog
@Test
public void m1() throws IOException, ClassNotFoundException {
String serFilePath = "e:\\dog.dat";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));
Dog dog = (Dog)ois.readObject();
System.out.println("====反序列化的后的dog===");
System.out.println(dog);
ois.close();
}
}
class Dog implements Serializable {
private String name;
private int age;
private String color;
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
public Dog(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
}
小伙伴们,记得老韩一键三连!!!