参考于韩顺平老师JAVA基础课程以及笔记
IO流知识框架图
文件
什么是文件?
简单来说,文件就是用来保存数据的地方
文件流(重要)
注意:输入或输出流针对的对象是java程序/内存而言的
文件操作
- 创建文件对象的方法和构造器
package com.file;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-7:55
*/
public class FileCreate {
public static void main(String[] args) {
}
@Test
//方式1 new File(String pathname)
public void create(){
File file = new File("D:\\filetext.txt"); //绝对路径
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
//方式2 new File(File parent,String child) //根据父目录文件+子路径构建
public void create02(){
File fileParent = new File("D:\\"); //创建父目录文件
String fileName ="filetext01.txt";
File file = new File(fileParent, fileName);
try {
file.createNewFile(); //只有执行该方法才是创建成功
System.out.println("创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式3:new File(String parentPath,String childPath)//根据父路径+子路径构建
@Test
public void create03(){
File file = new File("D:\\", "filetext03.jpg");
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 获取文件的相关信息
package com.file;
import com.sun.org.apache.xpath.internal.FoundIndex;
import org.junit.Test;
import java.io.File;
/**
* @Description
* @autor wzl
* @date 2022/8/17-8:09
* * 获取文件的信息
*/
public class FileInformation {
public static void main(String[] args) {
}
//获取文件的信息
@Test
public void info(){
//先创建文件对象
//注意:这里的文件是之前已经创建的
File file = new File("D:\\filetext.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());
}
}
- 创建/删除文件
注意:
package com.file;
import org.junit.Test;
import javax.sound.midi.Soundbank;
import java.io.File;
/**
* @Description
* @autor wzl
* @date 2022/8/17-8:20
*/
public class Directory {
public static void main(String[] args) {
}
@Test
//删除文件
public void test01(){
File file = new File("D:\\filetext.txt");
if(file.exists()){
if(file.delete()){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}else{
System.out.println("文件不存在");
}
}
@Test
//删除目录
public void test02(){
File file = new File("D:\\demo");
if(file.exists()){
if(file.delete()){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}else {
System.out.println("文件不存在");
}
}
@Test
//删除目录
public void test03(){
File file = new File("D:\\demo\\a\\b\\c");
if(file.exists()) {
System.out.println("文件目录已存在");
}else {
if(file.mkdirs()){
System.out.println("文件目录创建成功");
}else {
System.out.println("创建失败");
}
}
}
}
IO流原理以及流的分类
IO流原理
流的分类
注意:InputStream、OutputStream、Reader、Writer都是抽象类,它们不能直接实例化对象,而应该使用其子类进行实例化
Io流体系图
FileInputStream介绍
fileInputStream.read()
fileInputStream.read(byte[]b)
package com.file;
import org.junit.Test;
import java.io.*;
/**
* @Description
* @autor wzl
* @date 2022/8/17-9:01
* 演示FileinputStream的使用 字节输入流(文件---》程序)
*/
public class FileInputStream_ {
public static void main(String[] args) {
}
/*
演示读取文件,当文件中出现中文字符时,会出现乱码
使用read()读取
单个字节的读取,效率比较低----》使用 read(byte[]b)
*/
@Test
public void readFile01() {
String path = "D:\\hello.txt";
FileInputStream fileInputStream = null;
try {
//创建fileInputStream对象,用于读取文件
fileInputStream = new FileInputStream(path);
int readData = 0;
//fileInputStream.read()方法解释
//从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止。
//如果返回-1,表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char) readData); //转成char显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
使用 read(byte[]b)读取文件,提高效率
*/
@Test
public void readFile02() {
String path = "D:\\hello.txt";
//创建字节数组
byte[] buf=new byte[8];//一次读取8个字节
FileInputStream fileInputStream = null;
try {
//创建fileInputStream对象,用于读取文件
fileInputStream = new FileInputStream(path);
int readLen = 0;//接收实际读取的字节数
//fileInputStream.read(byte[] b)方法解释
//从该输入流读取最多b.length字节的数据到字节数组,此方法将阻塞,直到某些输入可用。
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
//public String(byte bytes[], int offset, int length)
System.out.print((new String(buf,0,readLen))); //转成字符串显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileOutPutStream介绍
- new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
- new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
fileOutputStream.write(char a)
fileOutputStream.write(byte[] b)
fileOutputStream.write(byte[] b,int off,int len)
package com.file;
import org.junit.Test;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-9:26
*/
public class FileOutPutStream_ {
public static void main(String[] args) {
}
/*
演示使用FileOutputStream 将数据写到文件中
如果该文件不存在,则自动创建该文件
*/
@Test
public void writeFile(){
String filePath="D:\\outtest.txt";
FileOutputStream fileOutputStream=null;
//1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
//2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
try {
fileOutputStream =new FileOutputStream(filePath,true);
//写入单个字节
//fileOutputStream.write('a');
//写入字符串
String str ="wzl,hello!";
//fileOutputStream.write(str.getBytes());
//写入指定长度的字符串
fileOutputStream.write(str.getBytes(),0,3);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 文件拷贝案例
注意:一边读,一边写,写的时候使用write(byte[]a,int off,int len)方法
package com.file;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-9:46
*/
public class FileCopy {
public static void main(String[] args) {
//1.创建文件输入流
FileInputStream fileInputStream=null;
//2.创建文件输出流
FileOutputStream fileOutputStream=null;
String srcFilePath="D:\\360极速浏览器下载\\app.mp4";
String destFilePath="D:\\app.mp4";
try {
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream=new FileOutputStream(destFilePath);
//定义一个字节数组,提高读取效果
byte[]buf =new byte[1024];
int readLen=0;
while ((readLen=fileInputStream.read(buf))!=-1){
//读取到后,就写入到文件
//一边读,一边写
fileOutputStream.write(buf,0,readLen);//一定使用这个方法,读多少,写多少
}
System.out.println("拷贝成功");
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭输入流
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//关闭输入流
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileReader 和FileWriter
- FileReader常用方法
package com.file;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-10:07
*/
public class FileReader_ {
public static void main(String[] args) {
}
/*
单个字符读取文件,可以有中文
*/
@Test
public void readFile01(){
FileReader fileReader=null;
String filePath="D:\\hello.txt";
try {
//1.创建对象
fileReader=new FileReader(filePath);
int data=0;
//2.单个字符循环读取
while ((data=fileReader.read())!=-1){
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
字符数组读取文件,可以有中文
*/
@Test
public void readFile02(){
FileReader fileReader=null;
String filePath="D:\\hello.txt";
try {
//1.创建对象
fileReader=new FileReader(filePath);
char[]buf=new char[8];//每次读取8个字符
int readLen=0;//实际读取的字符长度
//2.循环读取
//如果返回-1,说明文件介绍
while ((readLen=fileReader.read(buf))!=-1){
System.out.print(new String(buf,0,readLen));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- FileWriter常用方法
package com.file;
import org.junit.Test;
import java.io.FileWriter;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-10:20
*/
public class FileWriter_ {
public static void main(String[] args) {
}
/*
演示FileWriter
*/
@Test
public void fileWriter(){
String filePath="D:\\writer.txt";
FileWriter fileWriter=null;
char[] chars={'a','b','c'};
try {
fileWriter=new FileWriter(filePath);//默认覆盖原内容
//写入单个字符
fileWriter.write('a');
//写入指定数组
fileWriter.write(chars);
//写入指定数组的指定部分
fileWriter.write(chars,0,2);
fileWriter.write("哈哈哈哈".toCharArray(),0,4);
//写入整个字符串
fileWriter.write("你好啊");
//写入字符串指定部分
fileWriter.write("你多机多节点的",0,5);
//数据量大时,可以使用循环操作
} catch (IOException e) {
}finally {
try {
//fileWriter.flush();
fileWriter.close(); //相当于flush()+关闭
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
节点流和处理流
基本介绍
节点流vs处理流
- 模拟修饰器设计模式
创建Reader_抽象类,其中FileReader、StringReader分别继承Reader_抽象类,创建包装类BufferReader_,继承Reader_抽象类,并进行功能的扩展。
package com.file.test;
/**
* @Description
* @autor wzl
* @date 2022/8/17-11:03
*/
public abstract class Reader_ {
public void readFile(){}
public void readString(){}
}
package com.file.test;
/**
* @Description
* @autor wzl
* @date 2022/8/17-11:03
*/
public class FileReader_ extends Reader_ {
public void readFile(){
System.out.println("读取文件");
}
}
package com.file.test;
/**
* @Description
* @autor wzl
* @date 2022/8/17-11:04
*/
public class StringReader_ extends Reader_{
public void readString(){
System.out.println("读取了字符串");
}
}
package com.file.test;
import org.omg.CORBA.portable.ValueOutputStream;
/**
* @Description
* @autor wzl
* @date 2022/8/17-11:06
*/
public class BufferReader_ extends Reader_ {
private Reader_ reader_;
public BufferReader_(Reader_ reader_){
this.reader_=reader_;
}
public void readFile(){
reader_.readFile(); //调用子类的方法,使用super.readFile()没有效果,因为父类是抽象类,其实现是由子类实现的
}
//扩展功能
public void readFile(int num){
for (int i = 0; i < num; i++) {
reader_.readFile();
}
}
public void readString(int num){
for (int i = 0; i < num; i++) {
reader_.readString();
}
}
}
package com.file.test;
/**
* @Description
* @autor wzl
* @date 2022/8/17-11:10
*/
public class readerTest {
public static void main(String[] args) {
BufferReader_ bufferReader_ = new BufferReader_(new FileReader_());
BufferReader_ bufferReader1_ = new BufferReader_(new StringReader_());
bufferReader_.readFile();
bufferReader_.readFile(3);
bufferReader1_.readString(4);
}
}
BufferedReader 和 BufferedWriter介绍
- BufferedReader案例
package com.file;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* @Description
* @autor wzl
* @date 2022/8/17-11:36
*/
public class BufferedReader_ {
public static void main(String[] args) throws Exception {
String filePath="D:\\hello.txt";
//创建bufferedReader
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
//读取
String line;//按行读取,效率高
//当返回null时,标识文件读取完毕
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
//关闭流,只需要关闭BufferedReader,因为底层会自动的关闭节点流
bufferedReader.close();
/*
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
try {
in.close();// in 代表FileReader对象
} finally {
in = null;
cb = null;
}
}
}
*/
}
}
- BufferedWriter案例
package com.file.test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-14:32
*/
public class BufferedWriter_ {
public static void main(String[] args) throws IOException {
String filePath = "D:\\bufwriter.txt";
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));//以覆盖的方式
bufferedWriter.write("你好,好好学习额!");
bufferedWriter.newLine();//插入一个和系统相关的换行
bufferedWriter.write("你好,好好学习java");
bufferedWriter.newLine();
bufferedWriter.write("你好,好好学习区块链");
bufferedWriter.newLine();
bufferedWriter.close();
}
}
- 综合案例,完成文本文件拷贝
package com.file.test;
import java.io.*;
/**
* @Description
* @autor wzl
* @date 2022/8/17-14:37
*/
public class BufferedCopy_ {
public static void main(String[] args) throws IOException {
//BufferedReader和BufferedWriter是字符操作,不要去操作二进制文件(声音,视频,doc,pdf),可能造成文件损坏
//操作二进制文件使用BufferedInputStream 和 BufferedOutputStream
String srcFilePath="D:\\hello.txt";
String destFilePath="d:\\he.txt";
//定义输入和输出包装流
BufferedReader bufferedReader = new BufferedReader(new FileReader(srcFilePath));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(destFilePath));
//读取文件,按行读取,按行写入
String line;
while ((line=bufferedReader.readLine())!=null){
//按行写入
bufferedWriter.write(line);
//每读取一行,插入一个换行
bufferedWriter.newLine();
}
System.out.println("拷贝完毕");
//关闭流
bufferedReader.close();
bufferedWriter.close();
}
}
BufferedInputStream 和 BufferedOutputStream介绍
- 综合案例—拷贝二进制文件
package com.file.test;
import java.io.*;
/**
* @Description
* @autor wzl
* @date 2022/8/17-14:58
* 字节流可以操作二进制文件,当然也可以操作文本文件
*/
public class BufferedCopy2 {
public static void main(String[] args){
String srcFilePath = "D:\\app.mp4";
String destFilePath = "D:\\A\\a.mp4"; //如果文件目录是"D:\\A\\a.mp4",那么"D:\\A"必须存在,否则出现错误
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
//fileInputStream是 inputstream的子类
bufferedInputStream=new BufferedInputStream(new FileInputStream(srcFilePath));
bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(destFilePath));
//获取文件,按照字节读取
byte[] buf=new byte[1024];//一次读取1024个字节
int len=0;//实际读取的字节长度
while ((len=bufferedInputStream.read(buf))!=-1){
//边读边写
bufferedOutputStream.write(buf,0,len);
}
System.out.println("拷贝成功");
} catch (IOException e) {
e.printStackTrace();
}
try {
//关闭流
if(bufferedInputStream!=null){
bufferedInputStream.close();
}
if(bufferedOutputStream!=null){
bufferedOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象流ObjectInputStream 和 ObjectOutputStream
-
介绍
-
介绍
功能:提供了对基本类型或对象类型的序列化和反序列化的方法
ObjectOutputStream 提供 序列化功能
ObjectInputStream 提供 反序列化功能
- 案例代码—ObjectOutputStream—序列化
package com.file.test;
import java.io.*;
/**
* @Description
* @autor wzl
* @date 2022/8/17-15:41
* 演示ObjectOutStream的使用,完成数据的序列化
*/
public class ObjectOutStream_ {
public static void main(String[] args) throws IOException {
//序列化后,保存的文件格式,不是文本,而是按照它的格式来保存
String filePath="D:\\my.dat";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据
objectOutputStream.writeInt(100);//int-->Integer(实现了Serializable)
objectOutputStream.writeBoolean(true);//boolean-->Boolean(实现了Serializable)
objectOutputStream.writeChar('c');//char-->Character(实现了Serializable)
objectOutputStream.writeDouble(99.11);//double-->Double(实现了Serializable)
objectOutputStream.writeUTF("你好");//String(实现了Serializable)
objectOutputStream.writeObject(new Dog("小明",10));
//关闭流
objectOutputStream.close();
}
}
class Dog implements Serializable { //实现序列化接口,方可序列化
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
- 案例代码----ObjectInputStream----反序列化
package com.file.test;
import java.io.*;
/**
* @Description
* @autor wzl
* @date 2022/8/17-15:52
* * 反序列化演示
*/
public class ObjectInputStream_ {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 1.创建流对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\my.dat"));
// 2.读取, 注意顺序
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();//底层:object--》dog
System.out.println("运行类型"+dog.getClass());
System.out.println("dog信息"+dog);
//注意,当需要调用Dog方法,需要向下转型
//需要将dog类拷贝到可以引用的地方
Dog dog1=(Dog)dog;
System.out.println(dog1.getName());
// 3.关闭
ois.close();
System.out.println("以反序列化的方式读取(恢复)ok~");
}
}
class Dog implements Serializable { //实现序列化接口,方可序列化
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 注意事项
标准输入和输出流
package com.file.test;
import java.util.Scanner;
/**
* @Description
* @autor wzl
* @date 2022/8/17-16:19
*/
public class InputAndOutput {
public static void main(String[] args) {
//public final static InputStream in = null;
//System.in 编译类型 Inputstream
//System.in 运行类型 BufferedInputStream
//标准输入 键盘
System.out.println(System.in.getClass());
// public final static PrintStream out = null;
//编译类型 PrintStream
//运行类型 PrintStream
//表示标准输出 显示器
System.out.println(System.out.getClass());
Scanner scanner=new Scanner(System.in);
System.out.println("输入内容:");
String next = scanner.next();
System.out.println(next);
}
}
转换流InputStreamReader 和 OutputStreamWriter
- 介绍
解决文件乱码问题
- 案例----InputStreamReader
package com.file.test;
import java.io.*;
/**
* @Description
* @autor wzl
* @date 2022/8/17-16:38
* 读取乱码时
* 字节--->字符
*/
public class InputStreamReader_ {
public static void main(String[] args) throws IOException {
String filePath="D:\\hello.txt";
//1.把fileInputStream 转成InputStreamReader,指定编码格式;
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//2.将InputStreamReader 传入到 BufferedReader,提高读取效率
//BufferedReader bufferedReader = new BufferedReader(isr);
//将1和2连在一起
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));
//3.读取文件
String s = bufferedReader.readLine();
System.out.println("内容为:"+s);
//4.关闭流
bufferedReader.close();//包装流
}
}
- 案例—OutputStreamWriter
package com.file.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* @Description
* @autor wzl
* @date 2022/8/17-16:48
*/
public class outPutStream_ {
public static void main(String[] args) throws IOException {
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("D:\\aa.txt"),"gbk");
osw.write("你蛤蛤蛤蛤蛤蛤蛤");
osw.close();
System.out.println("保存成功");
}
}
打印流 PrintStream 和 PrintWriter
-
介绍
-
案例----PrintStream-字节打印
package com.file.test;
import java.io.IOException;
import java.io.PrintStream;
/**
* @Description
* @autor wzl
* @date 2022/8/17-17:05
*/
public class PrintStream_ {
public static void main(String[] args) throws IOException {
PrintStream printStream =System.out;
//在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
/*
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
*/
printStream.print("wzl,hello");
//因为 print 底层使用的是 write , 所以我们可以直接调用 write 进行打印/输出
printStream.write("hello,wzl".getBytes());
//我们可以去修改打印流输出的位置/设备
//1. 输出修改成到 "D:\\f1.txt"
//2. "hello, wzl~" 就会输出到 D:\\f1.txt
/*
public static void setOut(PrintStream out) {
checkIO();
setOut0(out); native方法,修改了out,因此接下来的输出都到指定的位置
}
*/
System.setOut(new PrintStream("D:\\f1.txt"));
System.out.println("wzl,hello"); //输出到文件,不是显示器
printStream.close();
}
}
- 案例----PrintWriter-字符打印
package com.file.test;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @Description
* @autor wzl
* @date 2022/8/17-16:58
*/
public class PrintWriter_ {
public static void main(String[] args) throws IOException {
//打印到显示器
//PrintWriter printWriter =new PrintWriter(System.out);
//printWriter.println("hhhh");
//打印到指定位置
PrintWriter printWriter =new PrintWriter(new FileWriter("D:\\ff.txt"));
printWriter.println("你好,北京");
printWriter.close(); //flush+关闭流,才会将数据写到文件中
}
}
Properties类
-
读取配置文件
-
使用传统方法读取
package com.file.test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-17:30
*/
public class Properties01 {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\mysql.properties"));
//循环读取
String str="";
while ((str=bufferedReader.readLine())!=null){
String[] split = str.split("=");
//获取指定的值
if("ip".equals(split[0])){
System.out.println(split[0]+"值为:"+split[1]);
}
}
bufferedReader.close();
}
}
- 使用Properties读取
package com.file.test;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/**
* @Description
* @autor wzl
* @date 2022/8/17-17:38
*/
public class Properties02 {
public static void main(String[] args) throws IOException {
//1.创建对象
Properties properties = new Properties();
//2.加载指定配置文件
properties.load(new FileReader("src\\mysql.properties"));
//3.把k-v显示到控制台
properties.list(System.out);
//4.根据key获取对应的值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println(user+"-->"+pwd);
}
}
package com.file.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
/**
* @Description
* @autor wzl
* @date 2022/8/17-17:44
*/
public class Properties03 {
public static void main(String[] args) throws IOException {
//创建配置文件,修改配置文件内容
Properties properties = new Properties();
//创建
//如果没有key,就是创建
//如果有key,就是修改
/*
/*
Properties 父类是 Hashtable , 底层就是 Hashtable 核心方法
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;//如果 key 存在,就替换
return old;
}
}
addEntry(hash, key, value, index);//如果是新 k, 就 addEntry
return null;
}
*/
properties.setProperty("charset", "utf8");
properties.setProperty("user", "约翰");
properties.setProperty("pwd", "13456");
//将k-v存储到文件中
properties.store(new FileOutputStream("src\\mysql1.properties"), null);
System.out.println("保存成功");
}
}
练习题
package com.file.test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* @Description
* @autor wzl
* @date 2022/8/17-17:55
*/
public class homework01 {
public static void main(String[] args) throws IOException {
String directoryPath="D:\\my";
File file = new File(directoryPath);
//目录
if(!file.exists()) {
//创建
if (file.mkdir()) {
System.out.println("目录创建成功");
}else {
System.out.println("目录创建失败");
}
}
String filePath=directoryPath+"\\test01.txt";
file = new File(filePath);
if(!file.exists()) {
//创建文件
if (file.createNewFile()) {
System.out.println("文件创建成功");
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
bufferedWriter.write("hello,world");
bufferedWriter.close();
} else {
System.out.println("文件创建失败");
}
}else {
System.out.println("文件已经存在,无需创建");
}
}
}
package com.file.test;
import java.io.*;
/**
* @Description
* @autor wzl
* @date 2022/8/17-18:12
*/
public class homework02 {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\hello.txt"));
//指定编码格式,解决乱码问题
//BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(new FileInputStream("d:\\hello.txt"),"gbk"));
String line="";
int lineNum=0;
while ((line=bufferedReader.readLine())!=null){
System.out.println(++lineNum+"--->"+line);
}
bufferedReader.close();
}
}
package com.file.test;
import java.io.*;
import java.util.Iterator;
import java.util.Properties;
/**
* @Description
* @autor wzl
* @date 2022/8/17-18:24
*/
public class homework03 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Properties properties =new Properties();
//读取配置文件
properties.load(new FileReader("src\\dog.properties"));
String name = properties.getProperty("name");
String age = properties.getProperty("age");
String color = properties.getProperty("color");
Cat cat = new Cat(name, Integer.parseInt(age), color);
System.out.println(cat);
//将创建的cat对象,序列化到cat.dat文件
String serPath="D:\\cat.dat";
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(serPath));
objectOutputStream.writeObject(cat);
objectOutputStream.close();
System.out.println("序列化成功");
//反序列化
String serrpath="D:\\cat.dat";
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(serrpath));
Cat catt = (Cat) objectInputStream.readObject();
System.out.println("反序列化后为:");
System.out.println(catt);
}
}
class Cat implements Serializable {
private String name;
private int age;
private String color;
public Cat(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
}