













import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
/*
文件:保存数据的地方,如word文档,txt文件.....
文件流
文件(磁盘) -----输入流-----> Java程序(内存)
Java程序(内存)-----输出流-----> 文件(磁盘)
//流:数据在数据源和程序之间经历的路径
//输入流:数据从数据源到程序的路径
//输出流:数据从程序到数据源的路径
常见文件操作
创建文件对象相关构造器和方法
new File(String pathname) //根据路径创建一个File对象
new File(File parent,String child) //根据父目录文件+子路径构建
new File(String parent,String child) //根据父目录+子路径构建
creatNewFile //创建新文件
获取文件相关信息(在Java中,目录也被当作文件)
getName //获取名字
getAbsolutePath //绝对路径
getParent //父级目录
length //文件大小(字节)
exists //是否存在
isFile //是否文件
isDirectory //是否目录
目录操作
mkdir //创建一级目录
mkdirs //创建多级目录
delete //删除空目录或文件
*/
public class IOStream01 {
public static void main(String[] args) {
}
//在D盘下,用三种不同方式创建文件news1.txt ,news2.txt ,news3.txt
//new File(String pathname)
@Test
public void creat01(){
String filePath = "d:\\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 creat02(){
File parentFile = new File("d:\\");
String child = "news2.txt";
File file = new File(parentFile,child);
try {
file.createNewFile();
System.out.println("创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//new File(String parent,String child)
@Test
public void creat03(){
String parentPath = "d:\\";
String filePath = "news3.txt";
File file = new File(parentPath, filePath);
try {
file.createNewFile();
System.out.println("创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void info(){
File file = new File("d:\\news1.txt");
//getName
System.out.println(file.getName());
//getAbsoluteFile
System.out.println(file.getAbsoluteFile());
//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());
}
//判断 d:\\news1.txt是否存在,如果存在就删除
@Test
public void m(){
String filePath = "d:\\news1.txt";
File file = new File(filePath);
if (file.exists()){
if (file.delete()){//delete
System.out.println(filePath + "删除成功");
}else{
System.out.println("删除失败");
}
}else{
System.out.println("文件不存在");
}
}
//创建多级目录
@Test
public void m2(){
String directoryPath = "d:\\demo\\a\\b";
File file = new File(directoryPath);
file.mkdirs();
System.out.println("创建成功");
}
}
/*
Java IO流原理
1.I/O是Input/Output的缩写,用于处理数据传输。如读/写文件,网络通讯...
2.Java程序中,对于数据的输入/输出操作以"流(stream)"的方式进行
3.java.io包下提供了各种"流"类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
4.输入input:读取外部数据(磁盘、光盘等存储设备)到程序(内存)中
5.输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中
流的分类
1.按操作数据单位不同分为:字节流(8bit),字符流(按字符)
2.按数据流的流向不同分为:输入流,输出流
3.按流的角色不同分为:节点流,处理流/包装流
字节流
字节输入流:InputStream
字节输出流:OutputStream
字符流
字符输入流:Reader
字符输出流:Writer
//抽象基类:InputStream、OutputStream、Reader、Writer
//Java的IO流设计40多个类,都是从上面四个抽象基类派生出来的
//由这四个类派生出来的子类名称都是以其父类名作为子类名后缀
*/
public class IOStream02 {
public static void main(String[] args) {
}
}
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
/*
InputStream字节输入流
InputStream抽象类是所有类字节输入流的超类
常用子类:
FileInputStream:文件输入流
BufferedInputStream:缓冲字节输入流
ObjectInputStream:对象字节输入流
*/
// 使用FileInputStream读取在D盘下的hello.txt文件
public class IOStream03 {
public static void main(String[] args) {
}
@Test
//使用read()读取
public void readFile01() {
String filePath = "d:\\hello.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//read()从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止。
//如果返回-1 , 表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
System.out.println((char)readData);//转成 char 显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
//使用read(byte[] b)读取文件,提高效率
public void readFile02() {
String filePath = "d:\\hello.txt";
//创建字节数组
byte[] buf = new byte[6]; //一次读取6个字节
int readLen = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//read(byte[] b)从该输入流读取最多 b.length 字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
//如果返回-1 , 表示读取完毕,如果读取正常, 返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1){
System.out.println(new String(buf, 0, readLen));//显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源.
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import org.junit.jupiter.api.Test;
import java.io.FileOutputStream;
import java.io.IOException;
/* 使用 FileOutputStream 在 hello02.txt 文件,中写入 “hello,java”
(如果文件不存在则会创建文件)
*/
public class IOStream04 {
public static void main(String[] args) {
}
@Test
public void writeFile(){
//创建FileOutputStream对象
String filePath = "d:\\hello02.txt";
FileOutputStream fileOutputStream = null;
try {
//new FileOutputStream(filePath),当写入内容时会覆盖原内容
//new FileOutputStream(filePath,true),写入内容时追加到最后
fileOutputStream = new FileOutputStream(filePath);
//写入一个字节write()
fileOutputStream.write('h');
fileOutputStream.write('e');
fileOutputStream.write('l');
fileOutputStream.write('l');
fileOutputStream.write('o');
//写入字符串
String str = "hello,world";
fileOutputStream.write(str.getBytes());//str.getBytes()把字符串转成字节数组
//write(byte[] b,int off,int len)
fileOutputStream.write(str.getBytes(),0,str.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/* 文件拷贝,将d盘的demo.jpg图片 拷贝到d盘的copy.jpg
思路
1.创建文件输入流,将文件读取到程序
2.创建文件输出流,将读取的文件写入到指定文件
*/
public class IOStream05 {
public static void main(String[] args) {
String srcFilePath = "d:\\demo.jpg";
String desFilePath = "d:\\copy.jpg";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream = new FileOutputStream(desFilePath);
//定义字节数组
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = fileInputStream.read(buf)) != -1){
//读取后写入目标文件,不能使用write(buf),可能出现错误,如最后剩余1字节,但还是写入1024
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();
}
}
}
}
import org.junit.jupiter.api.Test;
import java.io.FileReader;
import java.io.IOException;
/*
FileReader和FileWriter
FileReader和FileWriter是字符流,即按照字符来操作io
FileReader相关方法
1.new FileReader(File/String)
2.read:每次读取单个字符,返回该字符,到文件末尾返回-1
3.read(char[]):批量读取多个字符到数组,返回该字符数,到文件末尾返回-1
4.new String(char[]):将char[]转换成String
5.new String(char[],off,len):将char[]的指定部分转成String
FileWrite相关方法
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):写入字符串的指定部分
String类 toCharArray:将String转成char[]
//注:FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定文件
*/
// 使用FileReader从hello.txt读取内容
public class IOStream06 {
public static void main(String[] args) {
}
//使用read()读取
@Test
public void readFile01(){
String filePath = "d:\\hello.txt";
FileReader fileReader = null;
int data = ' ';
try {
fileReader = new FileReader(filePath);
//循环读取
while((data = fileReader.read()) != -1){
System.out.println((char)data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//使用read(char[])读取
@Test
public void readFile02(){
String filePath = "d:\\hello.txt";
FileReader fileReader = null;
int readLen = 0;
char[] buf = new char[6];
try{
fileReader = new FileReader(filePath);
//循环读取
while((readLen = fileReader.read(buf)) != -1){
System.out.println(new String(buf,0,readLen));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
import java.io.FileWriter;
import java.io.IOException;
/*
使用 FileWriter 在 study.txt 文件写入数据
*/
public class IOStream07 {
public static void main(String[] args) {
String filePath = "d:\\study.txt";
FileWriter fileWriter = null;
char[] chars = {'a','b','c'};
try {
fileWriter = new FileWriter(filePath);
//write(int)写入单个字符
fileWriter.write('H');
//write(char[])写入指定数组
fileWriter.write(chars);
//write(char[],off,len)写入指定数组的指定部分
fileWriter.write("我正在学习Java".toCharArray(),0,9);
//write(string)写入整个字符串
fileWriter.write("你好,Java");
//write(string,off,len)写入字符串的指定部分
fileWriter.write("演示Demo",0,6);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {//一定要关闭流才能真正的把数据写入目标文件
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
节点流和处理流
节点流:可以从一个特定的数据源读写数据,如FileReader,FileWriter
处理流:也叫包装流,是连接在已存在的流之上,为程序提供更为强大的读写功能,更加灵活如BufferedReader,BufferedWriter
1.节点流是底层流,直接跟数据源相连
2.处理流包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出
3.处理流对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连
处理流的功能主要体现
1.提高性能:增加缓冲的方式来提高输入输出效率
2.便捷操作:提供了一系列方法一次输入输出大批量数据,使用更加灵活方便
*/
// 模拟处理流设计模式
public class IOStream08 {
public static void main(String[] args) {
BufferedReader_ bufferedReader_ = new BufferedReader_(new FileReader_());
bufferedReader_.readFiles(5);
BufferedReader_ bufferedReader_1 = new BufferedReader_(new StringReader_());
bufferedReader_1.readStrings(5);
}
}
abstract class Reader_{//抽象类
public void readFile(){};
public void readString(){};
}
class FileReader_ extends Reader_{//节点流
public void readFile(){
System.out.println("读取文件....");
}
}
class StringReader_ extends Reader_{//节点流
public void readString(){
System.out.println("读取字符串....");
}
}
class BufferedReader_ extends Reader_{//处理流
private Reader_ reader_;//属性是Reader_类型
public BufferedReader_(Reader_ reader_) {
this.reader_ = reader_;
}
//多次读取文件
public void readFiles(int num){
for (int i = 0; i < num; i++) {
reader_.readFile();
}
}
//多次处理字符串
public void readStrings(int num){
for (int i = 0; i < num; i++) {
reader_.readString();
}
}
}
// BufferedReader和BufferedWriter 字符流,按字符读取数据,不能操作二进制文件(声音、视频、doc,pdf),可能造成文件损坏
// 关闭处理流时,只需要关闭外层流即可
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// 使用BufferedReader读取文本文件
public class IOStream09 {
public static void main(String[] args) throws IOException{
String filePath = "d:\\hello.txt";
//创建bufferedReader
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
//读取
String line;
//bufferedReader.readLine()按行读取,返回null时表示读取完毕
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
//关闭BufferedReader,因为底层会自动关闭节点流
bufferedReader.close();
}
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
// 使用BufferedWriter将"hello,Java",写入到文件
public class IOStream10 {
public static void main(String[] args) throws IOException{
String filePath = "d:\\hello2.txt";
//new FileWriter(filePath)覆盖
//new FileWriter(filePath,true)追加
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
bufferedWriter.write("hello,java");
bufferedWriter.newLine();//插入一个换行
bufferedWriter.write("hello,java");
bufferedWriter.newLine();
bufferedWriter.write("hello,java");
//关闭外层流
bufferedWriter.close();
}
}
import java.io.*;
// 结合使用BufferedReader和BufferedWriter,完成文本文件拷贝
public class IOStream11 {
public static void main(String[] args) {
String srcFilePath = "d:\\hello.txt";
String destFilePath = "d:\\hi.txt";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
try {
br = new BufferedReader(new FileReader(srcFilePath));
bw = new BufferedWriter(new FileWriter(destFilePath));
while ((line = br.readLine()) != null){
bw.write(line);//每读取一行就写入
bw.newLine();//插入换行符
}
System.out.println("拷贝文件成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null){
br.close();
}
if (bw != null){
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// BufferedInputStream和BufferedOutputStream
import java.io.*;
// 拷贝图片/音乐,使用BufferedInputStream和BufferedOutputStream
public class IOStream12 {
public static void main(String[] args) {
String srcFilePath = "d:\\demo.jpg";
String desFilePath = "d:\\copy.jpg";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//创建对象
try {
bis = new BufferedInputStream(new FileInputStream(srcFilePath));
bos = new BufferedOutputStream(new FileOutputStream(desFilePath));
//循环读取
byte[] buff = new byte[1024];
int readLen = 0;
while ((readLen = bis.read(buff)) != -1){
bos.write(buff,0,readLen);
}
} catch (IOException e) {
e.printStackTrace();
} finally {//关闭外层流
try {
if (bis != null){
bis.close();
}
if (bos != null){
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/*
对象处理流 ObjectInputStream和ObjectOutputStream
序列化和反序列化
1.序列化就是在保存数据时,保存数据的值和数据类型
2.反序列化就是在恢复数据时,恢复数据的值和数据类型
3.需要让某个对象支持序列化机制,则必须让其类是可序列化的
为了让某个类是可序列化的,就必须实现下面两个接口之一
Serializable //标记接口
Externalizable //该接口有方法需要实现,一般实现Serializable
ObjectOutputStream提供 序列化 功能
ObjectInputStream提供 反序列化 功能
细节
1.读写顺序要一致
2.序列化或反序列化对象,需要实现Serializable
3.序列化的类中建议添加SerialVersionUID,提高版本兼容性
4.序列化对象时,默认将所有属性都进行序列化,除了static或transient修饰的成员
5.序列化对象时,要求属性的类型也实现序列化接口
6.序列化具备继承性,如果某类已实现了序列化,则它的子类也默认实现了序列化
*/
// 使用ObjectOutputStream 序列化基本数据类型和一个Dog对象(name,age),并保存在data.dat文件中
public class IOStream13 {
public static void main(String[] args) throws Exception{
//序列化后,保存的文件格式,不是存文本,而是按照格式保存
String filePath = "d:\\data.dat";//指定文件
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到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(实现了Serializable)
//保存Dog对象
oos.writeObject(new Dog("富贵",6));
//关闭流
oos.close();
System.out.println("保存完毕");
}
}
class Dog implements Serializable {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
import java.io.FileInputStream;
import java.io.ObjectInputStream;
// 使用ObjectInputStream读取data.dat,并反序列化恢复数据
public class IOStream14 {
public static void main(String[] args) throws Exception {
String filePath = "d:\\data.dat";//指定文件
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
//读取,顺序应与保存数据的顺序一致
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());
System.out.println(ois.readObject());
//关闭外层流
ois.close();
}
}
/*
标准输入输出流
类型 默认设备
System.in InputStream 键盘
System.out PrintSteam 显示器
System.in 编译类型InputStream,运行类型BufferedInputStream
System.out编译类型PrintSteam,运行类型PrintSteam
System.out.println("") 是使用out对象将数据输出到显示器
Scanner(System.in) 是从标准输入 键盘接收数据
*/
public class IOStream15 {
public static void main(String[] args) {
System.out.println(System.in.getClass());//class java.io.BufferedInputStream
System.out.println(System.out.getClass());//class java.io.PrintStream
}
}
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/*
转换流 InputStreamReader和OutputStreamWriter
1.InputStreamReader是Reader的子类,可以将InputStream(字节流)包装成Reader(字符流)
2.OutputStreamWriter是Writer的子类,可以将OutputStream(字节流)包装成Writer(字符流)
3.当处理纯文本数据时,如果使用字符流效率更高,且可以解决中文问题,建议将字节流转成字符流
4.可以在使用时指定编码格式(如utf-8,gbk,gb2312,IOS8859-1等)
*/
// 将字节流FileInputStream转换成字符流InputSteamReader,对文件进行读取(按照utf-8格式)进而包装成BufferedReader
public class IOStream16 {
public static void main(String[] args) throws IOException {
String filePath = "d:\\hello.txt";
//把 FileInputStream 转成 InputStreamReader,指定编码gbk
InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf-8");
//把 InputStreamReader 传入 BufferedReader
BufferedReader br = new BufferedReader(isr);
//读取
String s = br.readLine();
System.out.println("读取的内容=" + s);
//关闭外层流
br.close();
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
// 将FileOutputStream字节流,转成字符流 OutputStreamWriter
public class IOStream17 {
public static void main(String[] args) throws IOException {
String filePath = "d:\\hello2.txt";
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
osw.write("hello,java语言");
osw.close();
}
}
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
/*
打印流 PrintSteam和PrintWriter
*/
public class IOStream18 {
public static void main(String[] args) throws IOException {
// 演示PrintSteam字节打印流
PrintStream out = System.out;
//在默认情况下,PrintStream输出数据位置是标准输出,即显示器
out.println("hello");
//因为print底层使用的是write,所以可以直接调用write进行输出
out.write("hello".getBytes());
out.close();
//修改输出位置/设备
//修改到d:\hello.txt
System.setOut(new PrintStream("d:\\hello.txt"));
System.out.println("hi,jack");//hi,jack被输出到d:\hello.txt
// 演示PrintWriter
PrintWriter printWriter = new PrintWriter("d:\\hello2.txt");
printWriter.print("hello,mary");
printWriter.close();
}
}
/*
Properties类
专门用于读写配置文件的集合类
1.配置文件格式
键=值
键=值
//注意键值对不需要有空格,值不需用引号括起来,默认类型为String
常见方法
load //加载配置文件的键值对到Properties对象
list //将数据显示到指定设备
getProperty(key) //根据键获取值
setProperty(key,value) //设置键值对到Properties对象
store //将Properties中的键值对存储到配置文件中
在idea中保存信息到配置文件,如果含有中文,会存储为Unicode码
*/
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
// 使用Properties类来读取mysql.properties文件
public class Properties_ {
public static void main(String[] args) throws IOException {
//1.创建Properties对象
Properties properties = new Properties();
//2.加载指定配置文件
properties.load(new FileReader("src\\mysql.properties"));
//3.把k-v显示控制台
properties.list(System.out);
//4.根据键获取对应值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println(user);
System.out.println(pwd);
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
// 使用Properties类创建配置文件,修改文件内容
public class Properties02 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
//创建文件
properties.setProperty("charset","utf-8");
properties.setProperty("user","tom");
properties.setProperty("psd","abc");//如果该文件没有key,就是创建,如果有,就是修改
//将k-v存储文件中
properties.store(new FileOutputStream("src\\mysql.properties"),null);
System.out.println("保存配置文件成功");
}
}