16Io流
什么是文件
文件是保存数据的地方,比如经常使用的word文档,txt文件,excel文件...都是文件。它既可以保存一张图片,也可以保存视频,声音
文件流
文件在程序中是以流的形式来操作的

流:数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
常用的文件操作:
创建文件对象相关构造器和方法
new File(String pathname) //根据路径构建一个File对象
new File(File parent,String child) //根据父目录文件+子路径构建
new File(String parent,String child) //根据父目录+子路径构建
createNewFile 创建新文件
点击查看代码
//方式1 new File(String pathname)
@Test
public void create01(){
String filePath = "E:\\slz\\note\\4.11\\new.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (Exception e) {
e.printStackTrace();
}
}
//方式2 new File(File parent,String child) //根据父目录文件+子路径构建
//E:\slz\note\4.11\new.txt
@Test
public void create02(){
File parentFile = new File("E:\\slz\\note\\4.11\\");
String fileName = "new2.txt";
//这里的file对象,在java程序中,只是一个对象
//只有执行了createNewFile方法,才会真正的,在磁盘创建该文件
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (Exception e) {
e.printStackTrace();
}
}
//方式3new File(String parent,String child) //根据父目录+子路径构建
//
@Test
public void create03(){
String parentPath = "E:\\";
String fileName = "slz\\note\\4.11\\new3.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (Exception e) {
e.printStackTrace();
}
}
获取文件的相关信息
getName:文件名、getAbsolutePath:文件绝对路径、getParent:文件父目录、length:文件大小(字节)、exists:文件是否存在、isFile:是不是一个文件、isDirectory:是不是一个目录
应用案例演示
如何获取到文件的大小,文件名,路径,父File,是文件还是目录(目录本质也是文件,一种特殊的文件),是否存在
点击查看代码
public static void main(String[] args) throws IOException {
File file = new File("E:\\slz\\note\\4.11\\new4.txt");
file.createNewFile();//创建文件
//常见方法,获取file对象的信息
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删除空目录或文件
应用案例演示
1.判断d:\\new1.txt是否存在,如果存在就删除
2.判断d:\\new是否存在,存在就删除,否则提示不存在
3.判断d:\\new\\a\\b目录是否存在,如果存在就提示已经存在,否则就创建
点击查看代码
//判断E:\slz\note\4.11\new.txt 是否存在,如果存在就删除
@Test
public void m1(){
String filePath = "E:\\slz\\note\\4.11\\new.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:\slz\note\4.11\new.txt 是否存在,存在就删除,否则提示不存在
//这里我们需要体会到,在java编程中,目录也被当做文件
@Test
public void m2(){
String filePath = "E:\\slz\\note\\4.11\\new2";
File file = new File(filePath);
if(file.exists()){
if (file.delete()) {
System.out.println(filePath+"删除成功");
} else {
System.out.println(filePath+"删除失败");
}
}else {
System.out.println("该文件不存在");
}
}
//判断d:\\new\\a\\b目录是否存在,如果存在就提示已经存在,否则就创建
@Test
public void m3(){
String directoryPath = "E:\\slz\\note\\4.11\\new2";
File file = new File(directoryPath);
if(file.exists()){
System.out.println(directoryPath+"存在");
}else {
if (file.mkdirs()) {//创建一级目录使用mkdir(),创建多级目录使用mkdirs()
System.out.println(directoryPath+"创建成功");
} else {
System.out.println(directoryPath+"创建失败");
}
}
}
Io流原理及流的分类
java IO流原理
1.I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。如读/写文件,网络通讯等
2.Java程序中,对于数据的输入/输出操作以"流(stream)"的方式进行
3.java.io包下提供了各种"流"类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
4.输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
5.输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中

流的分类
按操作数据单位不同分为:字节流(8 bit)二进制文件,字符流(按字符)
按数据流的流向不同分为:输入流,输出流
按流的的角色的不同分为:节点流,处理流/包装流
| (抽象基类)字节流 | 字节流 | 字符流 |
|---|---|---|
| 输入流 | InputStream | Reader |
| 输出流 | OutputStream | Writer |
1.java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。
2.由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
InputStream:字节输入流
InputStream抽象类是所有类字节输入流的超类
InputStream 常用的子类
1.FileInputStream:文件输入流
2.BufferedInputStream:缓冲字节输入流
3.ObjectInputStream:对象字节输入流
FileInputStream 应用实例
要求:请使用FileInputStream读取hello.txt文件,并将文件内容显示到控制台
点击查看代码
/**
* 演示读取文件...
* 单个字节的读取,效率比较低
* → 使用read(byte[] b)
* @throws FileNotFoundException
*/
@Test
public void readFile01() throws FileNotFoundException {
String filePath = "E:\\slz\\note\\4.11\\hello.txt";
int readData = 0;
FileInputStream fileInputStream = new FileInputStream(filePath);
try {
//创建 FileInputStream 对象,用于读取 文件
//从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止
//如果返回-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) 读取文件,提高效率
* @throws FileNotFoundException
*/
@Test
public void readFile02() throws FileNotFoundException {
String filePath = "E:\\slz\\note\\4.11\\hello.txt";
//字节数组
byte[] buf = new byte[8];//一次读取8个字节
int readLen = 0;
FileInputStream fileInputStream = null;
try {
//创建 FileInputStream 对象,用于读取 文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while ((readLen = fileInputStream.read(buf)) != -1) {
System.out.print(new String(buf,0, readLen));//显示
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileOutputStream应用实例
要求:请使用FileOutputStream 在a.txt文件,中写入"hello,world"。如果文件不存在,会创建文件(注意:前提是目录已经存在)
点击查看代码
/**
* 要求:请使用FileOutputStream 在a.txt文件,中写入"hello,world"。如果文件不存在,
* 会创建文件(注意:前提是目录已经存在)
*/
@Test
public void writeFile(){
//创建FileOutputStream对象
String filePath = "E:\\slz\\note\\4.11\\new3.txt";
FileOutputStream fileOutputStream = null;
try {
//得到 FileOutputStream对象 对象
//1.new FileOutputStream(filePath) 创建方式,当写入内容时,会覆盖原来的内容
//2.new FileOutputStream(filePath,true) 创建方式,当写入内容时,是追加到文件后面
fileOutputStream = new FileOutputStream(filePath,true);
//写入一个字节
//fileOutputStream.write('H');
//写入字符串
String str = "hello,world";
//str.getBytes() 可以把 字符串→字节数组
//fileOutputStream.write(str.getBytes());
//write(byte[] b, int off, int len)
/**
* 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流
* byte[] b:待写入的字节数组
* off:起始索引,从0开始计算
* len:写入的实际字节个数
*/
fileOutputStream.write(str.getBytes(),0,str.length());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//关闭
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:
1.new String(char[]):将char[]转换成String
2.new String(char[],off,len):将char[]的指定部分转换成String
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使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件
FileReader和FileWriter应用案例
要求:1.使用FileReader从hello.txt读取内容,并显示
点击查看代码
/**
* 单个字符读取文件
*/
@Test
public void readFile01(){
String filePath = "E:\\slz\\note\\4.11\\hello.txt";
FileReader fileReader = null;
int data = ' ';
//1.创建FileReader对象
try {
fileReader = new FileReader(filePath);
//循环读取 使用read,单个字符读取
while ((data = fileReader.read()) != -1){
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fileReader != null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 字符数组读取文件
*/
@Test
public void readFile02(){
String filePath = "E:\\slz\\note\\4.11\\hello.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 {
if(fileReader != null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
要求:2.使用FileWriter将"风雨之后,定见彩虹"写入到note.txt文件中
点击查看代码
public static void main(String[] args) {
String filePath = "E:\\slz\\note\\4.11\\note.txt";
//创建FileWriter对象
FileWriter fileWriter = null;
char[] chars = {'风','雨','之','后',',','定','见','彩','虹'};
try {
fileWriter = new FileWriter(filePath);
// 3.write(int):写入单个字符
// fileWriter.write('风');
// 4.write(char[]):写入指定数组
// fileWriter.write(chars);
// 5.write(char[],off,len):写入指定数组的指定部分
//fileWriter.write("风雨之后,定见彩虹".toCharArray(),0,9);
// 6.write(string):写入整个字符串
//fileWriter.write("风雨之后,定见彩虹");
// 7.write(string,off,len):写入字符串的指定部分
fileWriter.write("风雨之后,定见彩虹",0,9);
//在数据量大的情况下,可以使用循环操作
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//对应FileWriter,一定要关闭流,或者flush才能真正的把数据写入到文件
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
节点流
基本介绍
1.节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter

2.处理流(也叫包装流)是"连接"在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如BufferedReader、BufferedWriter

节点流和处理流的区别和联系:
1.节点流是底层流/低级流,直接跟数据源相接
2.处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。
3.处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连
处理流的功能主要体现在以下两个方面:
1.性能的提高:主要以增加缓冲的方式来提高输入输出的效率
2.操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便
处理流-BufferedReader 和 BufferedWriter
BufferedReader 和 BufferedWriter属于字符流,是按照字符来读取数据的
关闭时,只需要关闭外层流即可
应用案例
1.使用BufferedReader 读取文本文件,并显示在控制台
点击查看代码
public static void main(String[] args) throws IOException {
String filePath = "E:\\slz\\note\\4.11\\hello.txt";
//创建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 将"hello,今天阴天,等下好像就要下雨了,天气也降温了。"写入到文件中
点击查看代码
public static void main(String[] args) throws IOException {
String filePath = "E:\\slz\\note\\4.11\\ok.txt";
//创建BufferedWriter()
//1.new FileWriter(filePath,true)表示以追加的方式写入
//2.new FileWriter(filePath),表示以覆盖的方式写入
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
bufferedWriter.write("hello,今天阴天,");
bufferedWriter.newLine();//出入一个和系统相关的换行
bufferedWriter.write("等下好像就要下雨了,");
bufferedWriter.newLine();
bufferedWriter.write("天气也降温了。");
//关闭外层流即可,传入的new FileWriter(filePath),会在底层关闭
bufferedWriter.close();
}
3.总和使用BufferedReader 和BufferedWriter 完成 文本文件拷贝,注意文件编码
点击查看代码
public static void main(String[] args) {
//1.BufferedReader和BufferedWriter是安装字符操作
//2.不要去操作 二进制文件[声音,视频,doc,pdf等等],可能造成文件损坏
String srcFilePath = "E:\\slz\\note\\4.11\\ok.txt";
String destFilePath = "E:\\slz\\note\\4.11\\ok1.txt";
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();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(br != null){
br.close();
}
if(bw != null){
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
处理流-BufferedInputStream和BufferedOutputStream
BufferedInputStream是字节流,在创建BufferedInputStream时,会创建一个内部缓冲区数组
BufferedOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必每次对字节写入调用地层系统
点击查看代码
/**
* 演示使用BufferedOutputStream 和 BufferedInputStream使用
* 使用它们可以完成二进制文件拷贝
* 字节流可以操作二进制文件,也可以操作文本文件
*/
public static void main(String[] args) {
String srcFilePath = "E:\\slz\\note\\4.11\\bomb3.png";
String destFilePath = "E:\\slz\\note\\4.11\\b.png";
//创建BufferedOutputStream 和 BufferedInputStream对象
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){
bis.close();
}
if(bos != null){
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象流-ObjectInputStream和ObjectOutputStream
需求
1.将int num = 100这个int数据保存到文件中,注意不是100数字,而是int 100,并且,能够从文件中直接恢复int 100
2.将Dog dog = new Dog("小黄",3)这个dog对象保存到文件中,并且能够从文件恢复
3.上面的要求,就是能够将基本数据类型或者对象进行序列化和反序列化操作
序列化和反序列化
1.序列化就是在保存数据时,保存数据的值和数据类型
2.反序列化就是在恢复数据时,恢复数据的值和数据类型
3.需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须事先如下两个接口之一:
Serializable//这是一个标记接口
Externalizable
注意事项和细节:
1.读写顺序要一致
2.要求实现序列化或反序列化对象,需要实现Serializable
3.序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
4.序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
5.序列化对象时,要求里面属性的类型也需要实现序列化接口
6.序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化
应用案例
1.使用ObjectOutputStream序列化基本数据类型和一个Dog对象(name,age),并保存到data.dat文件中
点击查看代码
public class ObjectOutStream_ {
public static void main(String[] args) throws IOException {
//序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
String filePath = "E:\\slz\\note\\4.11\\ok2.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到 e:\data.dat
oos.writeInt(100);//int→Integer(实现了 Serializable)
oos.writeBoolean(true);//bollean→Boolean(实现了 Serializable)
oos.writeChar('a');//char → Character(实现了 Serializable)
oos.writeDouble(9.5);//double→Double(实现了 Serializable)
oos.writeUTF("今天下雨了");//String
//保存一个dog对象
oos.writeObject(new Dog("小白",20));
oos.close();
System.out.println("数据保存完毕(序列化形式)");
}
}
//如果需要序列化某个类的对象,必须实现 Serializable
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 +
'}';
}
}
2.使用ObjectInputStream读取ok.txt并反序列化恢复数据
点击查看代码
public static void main(String[] args) throws IOException, ClassNotFoundException {
//指定反序列化的文件
String filePath = "E:\\slz\\note\\4.11\\ok2.dat";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
//读取
//1.读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
//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();
System.out.println("运行类型="+dog.getClass());
System.out.println("dog信息="+dog);//底层 Object→Dog
//关闭流,关闭外层流即可,底层会关闭FIleInputStream流
ois.close();
}
转换流-InputStreamReader 和 OutputStreamWriter
1.InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流)
2.OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)
3.当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
4.可以在使用时指定编码格式(比如utf-8,gdk,db2312,ISO8859-1等)
应用案例
1.编程将字节流FileInputStream包装成(转换成)字符流InputStreamReader,对文件进行读取(按照utf-8格式),进而在包装成BufferedReader
点击查看代码
public static void main(String[] args) throws IOException {
String filePath = "E:\\slz\\note\\4.11\\软件.txt";
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(filePath), "utf-8"));
Boolean flag = true;
String line = "";
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
2.编程将字节流FileOutputStream包装成(转换成)字符流OutputStreamWriter,对文件进行写入(按照UTF-8格式,可以指定其他,比如gdk)
点击查看代码
public static void main(String[] args) throws IOException {
String filePath = "E:\\slz\\note\\4.11\\ok4.txt";
String charSet = "utf-8";
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
osw.write("hi,今天阴天");
osw.close();
System.out.println("按照"+ charSet+"保存文件成功");
}
打印流-PrintStream 和 PrintWriter
打印流只有输出流,没有输入流
点击查看代码
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("shen,hello");
//因为print底层使用的是write,所以我们可以直接调用write进行打印/输出
out.write("沈,你好".getBytes());
out.close();
//我们可以去修改打印流输出的位置/设备
//1.输出修改成 "E:\\slz\\note\\4.11\\ok4.txt"
//2."hello,沈"就会输出到"E:\\slz\\note\\4.11\\ok4.txt
//3. public static void setOut(PrintStream out) {
// checkIO();
// setOut0(out);
// }
System.setOut(new PrintStream("E:\\slz\\note\\4.11\\ok4.txt"));
System.out.println("hello,沈");
}
点击查看代码
public static void main(String[] args) throws IOException {
PrintWriter printWriter = new PrintWriter(new FileWriter("E:\\slz\\note\\4.11\\ok4.txt"));
printWriter.print("hi,杭州你好");
printWriter.close();//flush+关闭流,才会将数据写入到文件
}
Properties类
1.专门用于读写配置文件的集合类:
配置文件的格式:
键=值
键=值
2.注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String
3.Properties的场景方法
load:加载配置文件的键值对到Properties对象
list:将数据显示到指定设备
getProperty(key):根据键获取值
getProperty(key,value):设置键值对到Properties对象
store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会储存为unicode码。unicode码查询工具
http://tool.chinaz.com/tools/unicode.aspx
点击查看代码
public static void main(String[] args) throws IOException {
//读取 mysql.Properties 文件,并得到ip,user和pwd
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\mysql.properties"));
String line = "";
while ((line = bufferedReader.readLine()) != null){//循环读取
String[] split = line.split("=");
//如果我们需要指定的Ip值
if("ip".equals(split[0])) {
System.out.println(split[0] + "值是:" + split[1]);
}
System.out.println(split[0] + "值是:" + split[1]);
}
bufferedReader.close();
}
应用案例:
1.使用Properties类完成对mysql.properties的读取
点击查看代码
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);
//4.根据key-获取对应的值
String user = properties.getProperty("user");
String pw = properties.getProperty("pw");
System.out.println("用户名"+user);
System.out.println("密码"+pw);
}
2.使用Properties类添加key-val到新闻界mysql2.properties中
3.使用Properties类完成对mysql2.properties的读取,并修改某个key-val
点击查看代码
public static void main(String[] args) throws IOException {
//使用Properties 类来创建配置文件,修改配置文件内容
Properties properties = new Properties();
//创建
//1.如果该文件没有key就是创建,
//2.如果该文件有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;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
*/
properties.setProperty("charest","uts-8");
properties.setProperty("user","汤姆");//注意保存时,是中文的unicode码
properties.setProperty("pw","123123");
//将k-v存储文件中即可
properties.store(new FileOutputStream("src\\mysql2.properties"),"hello world");
System.out.println("保存配置文件成功~");
}
本章作业:
1.编程题:
1在判断e盘下是否有文件mytemp,如果没有就创建mytemp
2在E:\slz\note\4.11目录下,创建文件hello.txt
3如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了
4并且在hello.txt文件中,写入hello,world~
点击查看代码
public static void main(String[] args) throws IOException {
String directoryPath = "E:\\slz\\note\\4.11\\123";
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";//E:\slz\note\4.11\hello.txt
file = new File(filePath);
if (!file.exists()) {
//创建文件
if (file.createNewFile()) {
System.out.println(filePath + "创建成功~");
//如果文件存在,我们就使用BUfferedWriter字符输入流写入内容
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("hello,world~~ 沈");
bufferedWriter.close();
} else {
System.out.println(filePath + "创建失败~");
}
} else {
//如果文件已经存在,给出提示信息
System.out.println(filePath + "已经存在,不再重复创建...");
}
}
2.编程题:
要求:使用BufferedReader读取一个文本文件,为每行加上行号,再连同内容一并输出到屏幕上。
如果把文件编码改成gdk,出现中文乱码
1默认是按照utf-8处理,开始没有乱码
2提示:使用转换流,将FileInputStream→InputStreamReader→BufferedReader
点击查看代码
public static void main(String[] args) throws IOException {
String filePath = "E:\\slz\\note\\4.11\\软件.txt";
String line = "";
int sum = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gdk"));
while ((line = br.readLine())!= null){
System.out.println(++sum+" "+line);
}
br.close();
}
3.编程题:
1.要编写一个dog.properties
name=tom
age=5
color=red
2. 编写Dog类(name,age,color)创建一个dog对象,读取dog.properties用相应的内容完成属性初始化,并输出
3. 将创建的Dog对象,序列化到文件dog.dat文件
点击查看代码
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。dat文件
String serFilePath = "E:\\slz\\note\\4.11\\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:\\slz\\note\\4.11\\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;
public Dog(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
}

浙公网安备 33010602011771号