一、字节输出流
package cn.daitools;
import java.io.FileOutputStream;
import java.io.IOException;
//FileoutputStream 字节输出流
/*
输出到文件的都是字节,输出时会查询编码
* */
public class demo01 {
public static void main(String[] args) throws IOException {
/*使用文件路径创建文件输出流*/
final FileOutputStream fos = new FileOutputStream("file/a.txt");
/*写入单个字节*/
fos.write(98);
fos.write(98);
fos.write(98);
/*输出字节数组*/
final FileOutputStream fos1 = new FileOutputStream("file/b.txt");
byte[] a = "输出字节数组".getBytes();
fos1.write(a);
/*输出指定长度的字节数组
* utf-8编码中,一个汉字是三个字节,假如输出的字节不是三个,则会乱码
* */
final FileOutputStream fos2 = new FileOutputStream("file/c.txt");
fos2.write(a,0,4);
/*数据的追加续写*/
final FileOutputStream fos3 = new FileOutputStream("file/a.txt",true);
fos3.write("\r\n你好,我是大呆呆".getBytes());
/*关闭输出流*/
fos.close();
fos1.close();
fos2.close();
fos3.close();
}
}
二、字节输入流
package cn.daitools;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
//FileInputSteam 字节输入流
public class demo02 {
public static void main(String[] args) throws IOException {
/*使用文件名称来创建字节输入流*/
final FileInputStream fis1 = new FileInputStream("file/a.txt");
fis1.close();
/*使用文件对象的构造方法来创建文件输入流*/
final File file = new File("file/a.txt");
final FileInputStream fis2 = new FileInputStream(file);
fis2.close();
/*使用文件名称创建对象*/
final FileInputStream fis3 = new FileInputStream("file/c.txt");
final int r1 = fis3.read(); /*读入的是一个字节*/
System.out.println(r1);
System.out.println(fis3.read());
System.out.println(fis3.read());
System.out.println(fis3.read());
System.out.println(fis3.read());
System.out.println(fis3.read()); /*读入到文件最后返回的是-1*/
fis3.close();
/*循换读入字节*/
final FileInputStream fis4 = new FileInputStream("file/c.txt");
int len = 0;
while((len = fis4.read())!=-1)
System.out.println((char)len);
fis4.close();
/*读入字节数组*/
/*数据为abcde,但是每次读入的数据是两个字节,所以最后一次读入的数据为ed*/
/*原因是,每次两个字节位,但是最后一次只读入了一个字节*/
/*所以,就把第一个字节的位置给替换掉了1*/
final FileInputStream fis5 = new FileInputStream("file/c.txt");
byte[] bytes1 =new byte[2];
int len1 = 0;
while((len1 = fis5.read(bytes1))!=-1)
System.out.println(new String(bytes1));
fis5.close();
}
}
三、案例-复制文件
package cn.daitools;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*使用字节输入流和字节输出流*/
/*思路:先使用字节输入流输入文件,然后再使用字节输出流输出文件*/
public class copyFile {
public static void main(String[] args) throws IOException {
/*创建文件字节输入流*/
final FileInputStream fis = new FileInputStream("file/c.txt");
/*创建文件字节输出流*/
final FileOutputStream fos = new FileOutputStream("file/a/c.txt");
/*输入文件*/
int len = 0;
while((len=fis.read())!=-1)
fos.write(len);
/*使用字节数组的方式进行复制文件*/
byte[] bytes = new byte[1024];
while((len = fis.read(bytes))!=-1) /*这里是将读入的数据先放在字节数组里面*/
/*其中len表示的是有效的字节*/
fos.write(bytes);
fos.close();
fis.close();
}
}
四、字符流
package cn.daitools;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*FileReader 字符流;一次输入一个字符,不管该字符占用几个字节*/
/*
问题发现:使用字节流的时候,如果读入的是汉字,读入的字节不能组成一个汉字的话就会出现乱码的现象
但是,使用字符输入流的话就不会出现这种现象
因为每次输入输出都是以字符作为单位
字符流专门用来处理文本文件
* */
public class demo03 {
public static void main(String[] args) throws IOException {
/*文件字符流有两种构造方法
* 1、使用文件的路径来作为参数创建对象
* 2、使用文件对象来作为参数来创建对象
* */
/*创建文件字符输入流*/
/*使用文件路径*/
final FileReader fr = new FileReader("file/c.txt");
System.out.println(fr.read());
fr.close();
/*使用文件对象*/
File file = new File("file/a.txt");
final FileReader fr1 = new FileReader(file);
System.out.println(fr1.read());
int len = 0;
while((len = fr1.read())!=-1)
System.out.println((char)len);
fr1.close();
/*使用字符数组来读取字符*/
final FileReader fr2 = new FileReader(file);
char[] chars = new char[1024];
while((len = fr2.read(chars))!=-1)
System.out.println(new String(chars));
fr2.close();
/*创建字符输出流*/
final FileWriter fw = new FileWriter("file/a/c.txt", true);
fw.write("zxccb"); /*字符输出流可以直接输出字符串*/
fw.close();
}
}
五、字符流中的Flush
package cn.daitools;
import java.io.FileWriter;
import java.io.IOException;
/*字符流中的flush方法*/
/*flush 和 close的区别*/
/*flush是刷新流中的缓存,并不是关闭流对象,流的对象可以接着使用*/
/*而close是直接关闭流对象*/
public class demo04 {
public static void main(String[] args) throws IOException {
/*创建文件字符输出流*/
final FileWriter fw = new FileWriter("file/a/b.txt");
fw.write("你好,我是呆呆,现在测试刷新流中的数据");
fw.flush();
fw.write("\r\n刷新已经完成,还能继续使用字符输出流对象");
fw.close();
}
}
六、Try-catch
package cn.daitools;
import java.io.FileWriter;
import java.io.IOException;
/*使用try catch来捕获异常
*/
public class demo05 {
public static void main(String[] args) throws IOException {
/*创建流对象直接在try catc中进行*/
FileWriter fw = null;
try {
fw = new FileWriter("file/a/a.txt");
fw.write("使用Try catch进行捕获异常");
} catch (IOException e) {
System.out.println("有异常!");
} finally {
if(fw!=null){
try {
fw.close();
} catch (IOException e) {
System.out.println("关闭流有异常!");
}
}
}
/*JDK7.0新特性:可以直接在Try参数中直接创建流对象,流的操作放到Try的方法体中*/
/*这样操作不需要关闭流对象*/
try(FileWriter fw1 = new FileWriter("file/a/d.txt");){
fw1.write("测试Jdk7的新特性");
}catch (IOException e){
e.printStackTrace();
}
/*JDK9的新特性,在try的外面创建流对象,将流对象作为参数传入try的方法中
* try的方法体中进行流操作,同样不需要关闭流对象*/
// final FileWriter fw2 = new FileWriter("file/a/e.txt");
// try(fw2){
//
// }catch (IOException e){
// e.printStackTrace();
// }
/*使用匿名内部类创建流对象 不需要关闭*/
}
}
七、属性集Propeities
package cn.daitools;
import java.util.Properties;
import java.util.Set;
/*properties 继承map集合*/
public class dome06 {
public static void main(String[] args) {
/*创建属性集对象*/
final Properties prop = new Properties();
/*添加键值对元素*/
prop.setProperty("name","daidai");
prop.setProperty("age","21");
prop.setProperty("sex","男");
/*打印属性集对象*/
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("age"));
System.out.println(prop.getProperty("sex"));
/*遍历属性集,获取所有键的集合*/
final Set<String> strings = prop.stringPropertyNames();
for (String string : strings) {
/*打印键值对*/
System.out.println(string+"="+prop.getProperty(string));
}
}
}
八、案例-保存属性集、读取属性集
package cn.daitools;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
/*
java.util.Properties集合 extends Hashtable<k,v> implements Map<k,v>
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。
Properties集合是一个唯一和IO流相结合的集合
可以使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
可以使用Properties集合中的方法load,把硬盘中保存的文件(键值对),读取到集合中使用
属性列表中每个键及其对应值都是一个字符串。
Properties集合是一个双列集合,key和value默认都是字符串
*/
public class propAndFile {
public static void main(String[] args) throws IOException {
/*保存属性集数据到硬盘中*/
save();
/*遍历并打印硬盘中的数据*/
show();
}
private static void show() throws IOException {
/*创建一个属性集对象*/
final Properties prop = new Properties();
/*使用lode方法读取数据*/
prop.load(new FileReader("file/a/f.txt"));
/*遍历数据*/
for (String string : prop.stringPropertyNames()) {
System.out.println(string+"="+prop.getProperty(string));
}
}
private static void save() throws IOException {
/*创建一个属性集对象*/
final Properties prop = new Properties();
/*向属性集中添加数据*/
prop.setProperty("name","daidai");
prop.setProperty("age","21");
prop.setProperty("sex","男");
/*创建一个字符流输出对象*/
final FileWriter fw = new FileWriter("file/a/f.txt");
/*将属性集中的数据写入到硬盘中去*/
prop.store(fw,"save fw");
/*第一个参数为字符输出流对象,第二个对象为注释*/
/*注释的编码默认为unicode编码,所以不能使用中文*/
fw.close();
}
}
以下为黑马程序员笔记
day09【字节流、字符流】
主要内容
- IO流
- 字节流
- 字符流
- 异常处理
- Properties
教学目标
- 能够说出IO流的分类和功能
- 能够使用字节输出流写出数据到文件
- 能够使用字节输入流读取数据到程序
- 能够理解读取数据read(byte[])方法的原理
- 能够使用字节流完成文件的复制
- 能够使用FileWirter写数据到文件
- 能够说出FileWriter中关闭和刷新方法的区别
- 能够使用FileWriter写数据的5个方法
- 能够使用FileWriter写数据实现换行和追加写
- 能够使用FileReader读数据
- 能够使用FileReader读数据一次一个字符数组
- 能够使用Properties的load方法加载文件中配置信息
第一章 IO概述
1.1 什么是IO
生活中,你肯定经历过这样的场景。当你编辑一个文本文件,忘记了ctrl+s
,可能文件就白白编辑了。当你电脑上插入一个U盘,可以把一个视频,拷贝到你的电脑硬盘里。那么数据都是在哪些设备上的呢?键盘、内存、硬盘、外接设备等等。
我们把这种数据的传输,可以看做是一种数据的流动,按照流动的方向,以内存为基准,分为输入input
和输出output
,即流向内存是输入流,流出内存的输出流。
Java中I/O操作主要是指使用java.io
包下的内容,进行输入、输出操作。输入也叫做读取数据,输出也叫做作写出数据。
1.2 IO的分类
根据数据的流向分为:输入流和输出流。
- 输入流 :把数据从
其他设备
上读取到内存
中的流。 - 输出流 :把数据从
内存
中写出到其他设备
上的流。
格局数据的类型分为:字节流和字符流。
- 字节流 :以字节为单位,读写数据的流。
- 字符流 :以字符为单位,读写数据的流。
1.3 IO的流向说明图解
1.4 顶级父类们
输入流 | 输出流 | |
---|---|---|
字节流 | 字节输入流 InputStream | 字节输出流 OutputStream |
字符流 | 字符输入流 Reader | 字符输出流 Writer |
第二章 字节流
2.1 一切皆为字节
一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。
2.2 字节输出流【OutputStream】
java.io.OutputStream
抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。
public void close()
:关闭此输出流并释放与此流相关联的任何系统资源。public void flush()
:刷新此输出流并强制任何缓冲的输出字节被写出。public void write(byte[] b)
:将 b.length字节从指定的字节数组写入此输出流。public void write(byte[] b, int off, int len)
:从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。public abstract void write(int b)
:将指定的字节输出流。
小贴士:
close方法,当完成流的操作时,必须调用此方法,释放系统资源。
2.3 FileOutputStream类
OutputStream
有很多子类,我们从最简单的一个子类开始。
java.io.FileOutputStream
类是文件输出流,用于将数据写出到文件。
构造方法
public FileOutputStream(File file)
:创建文件输出流以写入由指定的 File对象表示的文件。public FileOutputStream(String name)
: 创建文件输出流以指定的名称写入文件。
当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。
- 构造举例,代码如下:
package com.itheima.demo01.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
java.io.OutputStream:字节输出流
此抽象类是表示输出字节流的所有类的超类。
定义了一些子类共性的成员方法:
- public void close() :关闭此输出流并释放与此流相关联的任何系统资源。
- public void flush() :刷新此输出流并强制任何缓冲的输出字节被写出。
- public void write(byte[] b):将 b.length字节从指定的字节数组写入此输出流。
- public void write(byte[] b, int off, int len) :从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。
- public abstract void write(int b) :将指定的字节输出流。
java.io.FileOutputStream extends OutputStream
FileOutputStream:文件字节输出流
作用:把内存中的数据写入到硬盘的文件中
构造方法:
FileOutputStream(String name)创建一个向具有指定名称的文件中写入数据的输出文件流。
FileOutputStream(File file) 创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
参数:写入数据的目的
String name:目的地是一个文件的路径
File file:目的地是一个文件
构造方法的作用:
1.创建一个FileOutputStream对象
2.会根据构造方法中传递的文件/文件路径,创建一个空的文件
3.会把FileOutputStream对象指向创建好的文件
写入数据的原理(内存-->硬盘)
java程序-->JVM(java虚拟机)-->OS(操作系统)-->OS调用写数据的方法-->把数据写入到文件中
字节输出流的使用步骤(重点):
1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
2.调用FileOutputStream对象中的方法write,把数据写入到文件中
3.释放资源(流使用会占用一定的内存,使用完毕要把内存清空,提供程序的效率)
*/
public class Demo01OutputStream {
public static void main(String[] args) throws IOException {
//1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地
FileOutputStream fos = new FileOutputStream("09_IOAndProperties\\a.txt");
//2.调用FileOutputStream对象中的方法write,把数据写入到文件中
//public abstract void write(int b) :将指定的字节输出流。
fos.write(97);
//3.释放资源(流使用会占用一定的内存,使用完毕要把内存清空,提供程序的效率)
//fos.close();
}
}
写出字节数据
- 写出字节:
write(int b)
方法,每次可以写出一个字节数据,代码使用演示:
package com.itheima.demo01.OutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
/*
一次写多个字节的方法:
- public void write(byte[] b):将 b.length字节从指定的字节数组写入此输出流。
- public void write(byte[] b, int off, int len) :从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。
*/
public class Demo02OutputStream {
public static void main(String[] args) throws IOException {
//创建FileOutputStream对象,构造方法中绑定要写入数据的目的地
FileOutputStream fos = new FileOutputStream(new File("09_IOAndProperties\\b.txt"));
//调用FileOutputStream对象中的方法write,把数据写入到文件中
//在文件中显示100,写个字节
fos.write(49);
fos.write(48);
fos.write(48);
/*
public void write(byte[] b):将 b.length字节从指定的字节数组写入此输出流。
一次写多个字节:
如果写的第一个字节是正数(0-127),那么显示的时候会查询ASCII表
如果写的第一个字节是负数,那第一个字节会和第二个字节,两个字节组成一个中文显示,查询系统默认码表(GBK)
*/
byte[] bytes = {65,66,67,68,69};//ABCDE
//byte[] bytes = {-65,-66,-67,68,69};//烤紻E
fos.write(bytes);
/*
public void write(byte[] b, int off, int len) :把字节数组的一部分写入到文件中
int off:数组的开始索引
int len:写几个字节
*/
fos.write(bytes,1,2);//BC
/*
写入字符的方法:可以使用String类中的方法把字符串,转换为字节数组
byte[] getBytes() 把字符串转换为字节数组
*/
byte[] bytes2 = "你好".getBytes();
System.out.println(Arrays.toString(bytes2));//[-28, -67, -96, -27, -91, -67]
fos.write(bytes2);
//释放资源
fos.close();
}
}
小贴士:
- 虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。
- 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
- 写出字节数组:
write(byte[] b)
,每次可以写出数组中的数据,代码使用演示:
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 字符串转换为字节数组
byte[] b = "黑马程序员".getBytes();
// 写出字节数组数据
fos.write(b);
// 关闭资源
fos.close();
}
}
输出结果:
黑马程序员
- 写出指定长度字节数组:
write(byte[] b, int off, int len)
,每次写出从off索引开始,len个字节,代码使用演示:
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 字符串转换为字节数组
byte[] b = "abcde".getBytes();
// 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
fos.write(b,2,2);
// 关闭资源
fos.close();
}
}
输出结果:
cd
数据追加续写
经过以上的演示,每次程序运行,创建输出流对象,都会清空目标文件中的数据。如何保留目标文件中数据,还能继续添加新数据呢?
public FileOutputStream(File file, boolean append)
: 创建文件输出流以写入由指定的 File对象表示的文件。public FileOutputStream(String name, boolean append)
: 创建文件输出流以指定的名称写入文件。
这两个构造方法,参数中都需要传入一个boolean类型的值,true
表示追加数据,false
表示清空原有数据。这样创建的输出流对象,就可以指定是否追加续写了,代码使用演示:
package com.itheima.demo01.OutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
追加写/续写:使用两个参数的构造方法
FileOutputStream(String name, boolean append)创建一个向具有指定 name 的文件中写入数据的输出文件流。
FileOutputStream(File file, boolean append) 创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
参数:
String name,File file:写入数据的目的地
boolean append:追加写开关
true:创建对象不会覆盖源文件,继续在文件的末尾追加写数据
false:创建一个新文件,覆盖源文件
写换行:写换行符号
windows:\r\n
linux:/n
mac:/r
*/
public class Demo03OutputStream {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("09_IOAndProperties\\c.txt",true);
for (int i = 1; i <=10 ; i++) {
fos.write("你好".getBytes());
fos.write("\r\n".getBytes());
}
fos.close();
}
}
写出换行
Windows系统里,换行符号是\r\n
。把
以指定是否追加续写了,代码使用演示:
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 定义字节数组
byte[] words = {97,98,99,100,101};
// 遍历数组
for (int i = 0; i < words.length; i++) {
// 写出一个字节
fos.write(words[i]);
// 写出一个换行, 换行符号转成数组写出
fos.write("\r\n".getBytes());
}
// 关闭资源
fos.close();
}
}
输出结果:
a
b
c
d
e
- 回车符
\r
和换行符\n
:
- 回车符:回到一行的开头(return)。
- 换行符:下一行(newline)。
- 系统中的换行:
- Windows系统里,每行结尾是
回车+换行
,即\r\n
;- Unix系统里,每行结尾只有
换行
,即\n
;- Mac系统里,每行结尾是
回车
,即\r
。从 Mac OS X开始与Linux统一。
2.4 字节输入流【InputStream】
java.io.InputStream
抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。它定义了字节输入流的基本共性功能方法。
public void close()
:关闭此输入流并释放与此流相关联的任何系统资源。public abstract int read()
: 从输入流读取数据的下一个字节。public int read(byte[] b)
: 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
小贴士:
close方法,当完成流的操作时,必须调用此方法,释放系统资源。
2.5 FileInputStream类
java.io.FileInputStream
类是文件输入流,从文件中读取字节。
构造方法
FileInputStream(File file)
: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。FileInputStream(String name)
: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有该文件,会抛出FileNotFoundException
。
- 构造举例,代码如下:
public class FileInputStreamConstructor throws IOException{
public static void main(String[] args) {
// 使用File对象创建流对象
File file = new File("a.txt");
FileInputStream fos = new FileInputStream(file);
// 使用文件名称创建流对象
FileInputStream fos = new FileInputStream("b.txt");
}
}
读取字节数据
- 读取字节:
read
方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回-1
,代码使用演示:
package com.itheima.demo02.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
/*
java.io.InputStream:字节输入流
此抽象类是表示字节输入流的所有类的超类。
定义了所有子类共性的方法:
int read()从输入流中读取数据的下一个字节。
int read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
void close() 关闭此输入流并释放与该流关联的所有系统资源。
java.io.FileInputStream extends InputStream
FileInputStream:文件字节输入流
作用:把硬盘文件中的数据,读取到内存中使用
构造方法:
FileInputStream(String name)
FileInputStream(File file)
参数:读取文件的数据源
String name:文件的路径
File file:文件
构造方法的作用:
1.会创建一个FileInputStream对象
2.会把FileInputStream对象指定构造方法中要读取的文件
读取数据的原理(硬盘-->内存)
java程序-->JVM-->OS-->OS读取数据的方法-->读取文件
字节输入流的使用步骤(重点):
1.创建FileInputStream对象,构造方法中绑定要读取的数据源
2.使用FileInputStream对象中的方法read,读取文件
3.释放资源
*/
public class Demo01InputStream {
public static void main(String[] args) throws IOException {
//1.创建FileInputStream对象,构造方法中绑定要读取的数据源
FileInputStream fis = new FileInputStream("09_IOAndProperties\\c.txt");
//2.使用FileInputStream对象中的方法read,读取文件
//int read()读取文件中的一个字节并返回,读取到文件的末尾返回-1
/*int len = fis.read();
System.out.println(len);//97 a
len = fis.read();
System.out.println(len);// 98 b
len = fis.read();
System.out.println(len);//99 c
len = fis.read();
System.out.println(len);//-1
len = fis.read();
System.out.println(len);//-1*/
/*
发现以上读取文件是一个重复的过程,所以可以使用循环优化
不知道文件中有多少字节,使用while循环
while循环结束条件,读取到-1的时候结束
布尔表达式(len = fis.read())!=-1
1.fis.read():读取一个字节
2.len = fis.read():把读取到的字节赋值给变量len
3.(len = fis.read())!=-1:判断变量len是否不等于-1
*/
int len = 0; //记录读取到的字节
while((len = fis.read())!=-1){
System.out.print(len);//abc
}
//3.释放资源
fis.close();
}
}
循环改进读取方式,代码使用演示:
package com.itheima.demo02.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
/*
字节输入流一次读取多个字节的方法:
int read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
明确两件事情:
1.方法的参数byte[]的作用?
起到缓冲作用,存储每次读取到的多个字节
数组的长度一把定义为1024(1kb)或者1024的整数倍
2.方法的返回值int是什么?
每次读取的有效字节个数
String类的构造方法
String(byte[] bytes) :把字节数组转换为字符串
String(byte[] bytes, int offset, int length) 把字节数组的一部分转换为字符串 offset:数组的开始索引 length:转换的字节个数
*/
public class Demo02InputStream {
public static void main(String[] args) throws IOException {
//创建FileInputStream对象,构造方法中绑定要读取的数据源
FileInputStream fis = new FileInputStream("09_IOAndProperties\\b.txt");
//使用FileInputStream对象中的方法read读取文件
//int read(byte[] b) 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
/*byte[] bytes = new byte[2];
int len = fis.read(bytes);
System.out.println(len);//2
//System.out.println(Arrays.toString(bytes));//[65, 66]
System.out.println(new String(bytes));//AB
len = fis.read(bytes);
System.out.println(len);//2
System.out.println(new String(bytes));//CD
len = fis.read(bytes);
System.out.println(len);//1
System.out.println(new String(bytes));//ED
len = fis.read(bytes);
System.out.println(len);//-1
System.out.println(new String(bytes));//ED*/
/*
发现以上读取时一个重复的过程,可以使用循环优化
不知道文件中有多少字节,所以使用while循环
while循环结束的条件,读取到-1结束
*/
byte[] bytes = new byte[1024];//存储读取到的多个字节
int len = 0; //记录每次读取的有效字节个数
while((len = fis.read(bytes))!=-1){
//String(byte[] bytes, int offset, int length) 把字节数组的一部分转换为字符串 offset:数组的开始索引 length:转换的字节个数
System.out.println(new String(bytes,0,len));
}
//释放资源
fis.close();
}
}
小贴士:
- 虽然读取了一个字节,但是会自动提升为int类型。
- 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
- 使用字节数组读取:
read(byte[] b)
,每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回-1
,代码使用演示:
public class FISRead {
public static void main(String[] args) throws IOException{
// 使用文件名称创建流对象.
FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
// 定义变量,作为有效个数
int len ;
// 定义字节数组,作为装字节数据的容器
byte[] b = new byte[2];
// 循环读取
while (( len= fis.read(b))!=-1) {
// 每次读取后,把数组变成字符串打印
System.out.println(new String(b));
}
// 关闭资源
fis.close();
}
}
输出结果:
ab
cd
ed
错误数据d
,是由于最后一次读取时,只读取一个字节e
,数组中,上次读取的数据没有被完全替换,所以要通过len
,获取有效的字节,代码使用演示:
public class FISRead {
public static void main(String[] args) throws IOException{
// 使用文件名称创建流对象.
FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
// 定义变量,作为有效个数
int len ;
// 定义字节数组,作为装字节数据的容器
byte[] b = new byte[2];
// 循环读取
while (( len= fis.read(b))!=-1) {
// 每次读取后,把数组的有效字节部分,变成字符串打印
System.out.println(new String(b,0,len));// len 每次读取的有效字节个数
}
// 关闭资源
fis.close();
}
}
输出结果:
ab
cd
e
小贴士:
使用数组读取,每次读取多个字节,减少了系统间的IO操作次数,从而提高了读写的效率,建议开发中使用。
2.6 字节流练习:图片复制
复制原理图解
案例实现
复制图片文件,代码使用演示:
package com.itheima.demo03.CopyFile;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
文件复制练习:一读一写
明确:
数据源: c:\\1.jpg
数据的目的地: d:\\1.jpg
文件复制的步骤:
1.创建一个字节输入流对象,构造方法中绑定要读取的数据源
2.创建一个字节输出流对象,构造方法中绑定要写入的目的地
3.使用字节输入流对象中的方法read读取文件
4.使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中
5.释放资源
*/
public class Demo01CopyFile {
public static void main(String[] args) throws IOException {
long s = System.currentTimeMillis();
//1.创建一个字节输入流对象,构造方法中绑定要读取的数据源
FileInputStream fis = new FileInputStream("c:\\1.jpg");
//2.创建一个字节输出流对象,构造方法中绑定要写入的目的地
FileOutputStream fos = new FileOutputStream("d:\\1.jpg");
//一次读取一个字节写入一个字节的方式
//3.使用字节输入流对象中的方法read读取文件
/*int len = 0;
while((len = fis.read())!=-1){
//4.使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中
fos.write(len);
}*/
//使用数组缓冲读取多个字节,写入多个字节
byte[] bytes = new byte[1024];
//3.使用字节输入流对象中的方法read读取文件
int len = 0;//每次读取的有效字节个数
while((len = fis.read(bytes))!=-1){
//4.使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中
fos.write(bytes,0,len);
}
//5.释放资源(先关写的,后关闭读的;如果写完了,肯定读取完毕了)
fos.close();
fis.close();
long e = System.currentTimeMillis();
System.out.println("复制文件共耗时:"+(e-s)+"毫秒");
}
}
小贴士:
流的关闭原则:先开后关,后开先关。
第三章 字符流
当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。
package com.itheima.Demo04.Reader;
import java.io.FileInputStream;
import java.io.IOException;
/*
使用字节流读取中文文件
1个中文
GBK:占用两个字节
UTF-8:占用3个字节
*/
public class Demo01InputStream {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("09_IOAndProperties\\c.txt");
int len = 0;
while((len = fis.read())!=-1){
System.out.println((char)len);
}
fis.close();
}
}
3.1 字符输入流【Reader】
java.io.Reader
抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入流的基本共性功能方法。
public void close()
:关闭此流并释放与此流相关联的任何系统资源。public int read()
: 从输入流读取一个字符。public int read(char[] cbuf)
: 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。
3.2 FileReader类
java.io.FileReader
类是读取字符文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。
小贴士:
字符编码:字节与字符的对应规则。Windows系统的中文编码默认是GBK编码表。
idea中UTF-8
字节缓冲区:一个字节数组,用来临时存储字节数据。
构造方法
FileReader(File file)
: 创建一个新的 FileReader ,给定要读取的File对象。FileReader(String fileName)
: 创建一个新的 FileReader ,给定要读取的文件的名称。
当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream 。
- 构造举例,代码如下:
package com.itheima.Demo04.Reader;
import java.io.FileReader;
import java.io.IOException;
/*
java.io.Reader:字符输入流,是字符输入流的最顶层的父类,定义了一些共性的成员方法,是一个抽象类
共性的成员方法:
int read() 读取单个字符并返回。
int read(char[] cbuf)一次读取多个字符,将字符读入数组。
void close() 关闭该流并释放与之关联的所有资源。
java.io.FileReader extends InputStreamReader extends Reader
FileReader:文件字符输入流
作用:把硬盘文件中的数据以字符的方式读取到内存中
构造方法:
FileReader(String fileName)
FileReader(File file)
参数:读取文件的数据源
String fileName:文件的路径
File file:一个文件
FileReader构造方法的作用:
1.创建一个FileReader对象
2.会把FileReader对象指向要读取的文件
字符输入流的使用步骤:
1.创建FileReader对象,构造方法中绑定要读取的数据源
2.使用FileReader对象中的方法read读取文件
3.释放资源
*/
public class Demo02Reader {
public static void main(String[] args) throws IOException {
//1.创建FileReader对象,构造方法中绑定要读取的数据源
FileReader fr = new FileReader("09_IOAndProperties\\c.txt");
//2.使用FileReader对象中的方法read读取文件
//int read() 读取单个字符并返回。
/*int len = 0;
while((len = fr.read())!=-1){
System.out.print((char)len);
}*/
//int read(char[] cbuf)一次读取多个字符,将字符读入数组。
char[] cs = new char[1024];//存储读取到的多个字符
int len = 0;//记录的是每次读取的有效字符个数
while((len = fr.read(cs))!=-1){
/*
String类的构造方法
String(char[] value) 把字符数组转换为字符串
String(char[] value, int offset, int count) 把字符数组的一部分转换为字符串 offset数组的开始索引 count转换的个数
*/
System.out.println(new String(cs,0,len));
}
//3.释放资源
fr.close();
}
}
读取字符数据
- 读取字符:
read
方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1
,循环读取,代码使用演示:
public class FRRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存数据
int b ;
// 循环读取
while ((b = fr.read())!=-1) {
System.out.println((char)b);
}
// 关闭资源
fr.close();
}
}
输出结果:
黑
马
程
序
员
小贴士:虽然读取了一个字符,但是会自动提升为int类型。
- 使用字符数组读取:
read(char[] cbuf)
,每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-1
,代码使用演示:
public class FRRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存有效字符个数
int len ;
// 定义字符数组,作为装字符数据的容器
char[] cbuf = new char[2];
// 循环读取
while ((len = fr.read(cbuf))!=-1) {
System.out.println(new String(cbuf));
}
// 关闭资源
fr.close();
}
}
输出结果:
黑马
程序
员序
获取有效的字符改进,代码使用演示:
public class FISRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存有效字符个数
int len ;
// 定义字符数组,作为装字符数据的容器
char[] cbuf = new char[2];
// 循环读取
while ((len = fr.read(cbuf))!=-1) {
System.out.println(new String(cbuf,0,len));
}
// 关闭资源
fr.close();
}
}
输出结果:
黑马
程序
员
3.3 字符输出流【Writer】
java.io.Writer
抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。它定义了字节输出流的基本共性功能方法。
void write(int c)
写入单个字符。void write(char[] cbuf)
写入字符数组。abstract void write(char[] cbuf, int off, int len)
写入字符数组的某一部分,off数组的开始索引,len写的字符个数。void write(String str)
写入字符串。void write(String str, int off, int len)
写入字符串的某一部分,off字符串的开始索引,len写的字符个数。void flush()
刷新该流的缓冲。void close()
关闭此流,但要先刷新它。
3.4 FileWriter类
java.io.FileWriter
类是写出字符到文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。
构造方法
FileWriter(File file)
: 创建一个新的 FileWriter,给定要读取的File对象。FileWriter(String fileName)
: 创建一个新的 FileWriter,给定要读取的文件的名称。
当你创建一个流对象时,必须传入一个文件路径,类似于FileOutputStream。
- 构造举例,代码如下:
public class FileWriterConstructor {
public static void main(String[] args) throws IOException {
// 使用File对象创建流对象
File file = new File("a.txt");
FileWriter fw = new FileWriter(file);
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("b.txt");
}
}
基本写出数据
写出字符:write(int b)
方法,每次可以写出一个字符数据,代码使用演示:
package com.itheima.Demo05Writer;
import java.io.FileWriter;
import java.io.IOException;
/*
java.io.Writer:字符输出流,是所有字符输出流的最顶层的父类,是一个抽象类
共性的成员方法:
- void write(int c) 写入单个字符。
- void write(char[] cbuf)写入字符数组。
- abstract void write(char[] cbuf, int off, int len)写入字符数组的某一部分,off数组的开始索引,len写的字符个数。
- void write(String str)写入字符串。
- void write(String str, int off, int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
- void flush()刷新该流的缓冲。
- void close() 关闭此流,但要先刷新它。
java.io.FileWriter extends OutputStreamWriter extends Writer
FileWriter:文件字符输出流
作用:把内存中字符数据写入到文件中
构造方法:
FileWriter(File file)根据给定的 File 对象构造一个 FileWriter 对象。
FileWriter(String fileName) 根据给定的文件名构造一个 FileWriter 对象。
参数:写入数据的目的地
String fileName:文件的路径
File file:是一个文件
构造方法的作用:
1.会创建一个FileWriter对象
2.会根据构造方法中传递的文件/文件的路径,创建文件
3.会把FileWriter对象指向创建好的文件
字符输出流的使用步骤(重点):
1.创建FileWriter对象,构造方法中绑定要写入数据的目的地
2.使用FileWriter中的方法write,把数据写入到内存缓冲区中(字符转换为字节的过程)
3.使用FileWriter中的方法flush,把内存缓冲区中的数据,刷新到文件中
4.释放资源(会先把内存缓冲区中的数据刷新到文件中)
*/
public class Demo01Writer {
public static void main(String[] args) throws IOException {
//1.创建FileWriter对象,构造方法中绑定要写入数据的目的地
FileWriter fw = new FileWriter("09_IOAndProperties\\d.txt");
//2.使用FileWriter中的方法write,把数据写入到内存缓冲区中(字符转换为字节的过程)
//void write(int c) 写入单个字符。
fw.write(97);
//3.使用FileWriter中的方法flush,把内存缓冲区中的数据,刷新到文件中
//fw.flush();
//4.释放资源(会先把内存缓冲区中的数据刷新到文件中)
fw.close();
}
}
小贴士:
- 虽然参数为int类型四个字节,但是只会保留一个字符的信息写出。
- 未调用close方法,数据只是保存到了缓冲区,并未写出到文件中。
关闭和刷新
因为内置缓冲区的原因,如果不关闭输出流,无法写出字符到文件中。但是关闭的流对象,是无法继续写出数据的。如果我们既想写出数据,又想继续使用流,就需要flush
方法了。
flush
:刷新缓冲区,流对象可以继续使用。close
:先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。
代码使用演示:
package com.itheima.Demo05Writer;
import java.io.FileWriter;
import java.io.IOException;
/*
flush方法和close方法的区别
- flush :刷新缓冲区,流对象可以继续使用。
- close: 先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。
*/
public class Demo02CloseAndFlush {
public static void main(String[] args) throws IOException {
//1.创建FileWriter对象,构造方法中绑定要写入数据的目的地
FileWriter fw = new FileWriter("09_IOAndProperties\\e.txt");
//2.使用FileWriter中的方法write,把数据写入到内存缓冲区中(字符转换为字节的过程)
//void write(int c) 写入单个字符。
fw.write(97);
//3.使用FileWriter中的方法flush,把内存缓冲区中的数据,刷新到文件中
fw.flush();
//刷新之后流可以继续使用
fw.write(98);
//4.释放资源(会先把内存缓冲区中的数据刷新到文件中)
fw.close();
//close方法之后流已经关闭了,已经从内存中消失了,流就不能再使用了
fw.write(99);//IOException: Stream closed
}
}
小贴士:即便是flush方法写出了数据,操作的最后还是要调用close方法,释放系统资源。
写出其他数据
- 写出字符数组 :
write(char[] cbuf)
和write(char[] cbuf, int off, int len)
,每次可以写出字符数组中的数据,用法类似FileOutputStream,代码使用演示:
package com.itheima.Demo05Writer;
import java.io.FileWriter;
import java.io.IOException;
/*
字符输出流写数据的其他方法
- void write(char[] cbuf)写入字符数组。
- abstract void write(char[] cbuf, int off, int len)写入字符数组的某一部分,off数组的开始索引,len写的字符个数。
- void write(String str)写入字符串。
- void write(String str, int off, int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
*/
public class Demo03Writer {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("09_IOAndProperties\\f.txt");
char[] cs = {'a','b','c','d','e'};
//void write(char[] cbuf)写入字符数组。
fw.write(cs);//abcde
//void write(char[] cbuf, int off, int len)写入字符数组的某一部分,off数组的开始索引,len写的字符个数。
fw.write(cs,1,3);//bcd
//void write(String str)写入字符串。
fw.write("传智播客");//传智播客
//void write(String str, int off, int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
fw.write("黑马程序员",2,3);//程序员
fw.close();
}
}
- 写出字符串:
write(String str)
和write(String str, int off, int len)
,每次可以写出字符串中的数据,更为方便,代码使用演示:
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("fw.txt");
// 字符串
String msg = "黑马程序员";
// 写出字符数组
fw.write(msg); //黑马程序员
// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
fw.write(msg,2,2); // 程序
// 关闭资源
fos.close();
}
}
- 续写和换行:操作类似于FileOutputStream。
package com.itheima.Demo05Writer;
import java.io.FileWriter;
import java.io.IOException;
/*
续写和换行
续写,追加写:使用两个参数的构造方法
FileWriter(String fileName, boolean append)
FileWriter(File file, boolean append)
参数:
String fileName,File file:写入数据的目的地
boolean append:续写开关 true:不会创建新的文件覆盖源文件,可以续写; false:创建新的文件覆盖源文件
换行:换行符号
windows:\r\n
linux:/n
mac:/r
*/
public class Demo04Writer {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("09_IOAndProperties\\g.txt",true);
for (int i = 0; i <10 ; i++) {
fw.write("HelloWorld"+i+"\r\n");
}
fw.close();
}
}
小贴士:字符流,只能操作文本文件,不能操作图片,视频等非文本文件。
当我们单纯读或者写文本文件时 使用字符流 其他情况使用字节流
第四章 IO异常的处理
JDK7前处理
之前的入门练习,我们一直把异常抛出,而实际开发中并不能这样处理,建议使用try...catch...finally
代码块,处理异常部分,代码使用演示:
package com.itheima.demo06.trycatch;
import java.io.FileWriter;
import java.io.IOException;
/*
在jdk1.7之前使用try catch finally 处理流中的异常
格式:
try{
可能会产出异常的代码
}catch(异常类变量 变量名){
异常的处理逻辑
}finally{
一定会指定的代码
资源释放
}
*/
public class Demo01TryCatch {
public static void main(String[] args) {
//提高变量fw的作用域,让finally可以使用
//变量在定义的时候,可以没有值,但是使用的时候必须有值
//fw = new FileWriter("09_IOAndProperties\\g.txt",true); 执行失败,fw没有值,fw.close会报错
FileWriter fw = null;
try{
//可能会产出异常的代码
fw = new FileWriter("w:\\09_IOAndProperties\\g.txt",true);
for (int i = 0; i <10 ; i++) {
fw.write("HelloWorld"+i+"\r\n");
}
}catch(IOException e){
//异常的处理逻辑
System.out.println(e);
}finally {
//一定会指定的代码
//创建对象失败了,fw的默认值就是null,null是不能调用方法的,会抛出NullPointerException,需要增加一个判断,不是null在把资源释放
if(fw!=null){
try {
//fw.close方法声明抛出了IOException异常对象,所以我们就的处理这个异常对象,要么throws,要么try catch
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JDK7的处理(扩展知识点了解内容)
还可以使用JDK7优化后的try-with-resource
语句,该语句确保了每个资源在语句结束时关闭。所谓的资源(resource)是指在程序完成后,必须关闭的对象。
格式:
try (创建流对象语句,如果多个,使用';'隔开) {
// 读写数据
} catch (IOException e) {
e.printStackTrace();
}
代码使用演示:
package com.itheima.demo06.trycatch;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
JDK7的新特性
在try的后边可以增加一个(),在括号中可以定义流对象
那么这个流对象的作用域就在try中有效
try中的代码执行完毕,会自动把流对象释放,不用写finally
格式:
try(定义流对象;定义流对象....){
可能会产出异常的代码
}catch(异常类变量 变量名){
异常的处理逻辑
}
*/
public class Demo02JDK7 {
public static void main(String[] args) {
try(//1.创建一个字节输入流对象,构造方法中绑定要读取的数据源
FileInputStream fis = new FileInputStream("c:\\1.jpg");
//2.创建一个字节输出流对象,构造方法中绑定要写入的目的地
FileOutputStream fos = new FileOutputStream("d:\\1.jpg");){
//可能会产出异常的代码
//一次读取一个字节写入一个字节的方式
//3.使用字节输入流对象中的方法read读取文件
int len = 0;
while((len = fis.read())!=-1){
//4.使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中
fos.write(len);
}
}catch (IOException e){
//异常的处理逻辑
System.out.println(e);
}
}
}
JDK9的改进(扩展知识点了解内容)
JDK9中try-with-resource
的改进,对于引入对象的方式,支持的更加简洁。被引入的对象,同样可以自动关闭,无需手动close,我们来了解一下格式。
改进前格式:
// 被final修饰的对象
final Resource resource1 = new Resource("resource1");
// 普通对象
Resource resource2 = new Resource("resource2");
// 引入方式:创建新的变量保存
try (Resource r1 = resource1;
Resource r2 = resource2) {
// 使用对象
}
改进后格式:
// 被final修饰的对象
final Resource resource1 = new Resource("resource1");
// 普通对象
Resource resource2 = new Resource("resource2");
// 引入方式:直接引入
try (resource1; resource2) {
// 使用对象
}
改进后,代码使用演示:
package com.itheima.demo06.trycatch;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
JDK9新特性
try的前边可以定义流对象
在try后边的()中可以直接引入流对象的名称(变量名)
在try代码执行完毕之后,流对象也可以释放掉,不用写finally
格式:
A a = new A();
B b = new B();
try(a,b){
可能会产出异常的代码
}catch(异常类变量 变量名){
异常的处理逻辑
}
*/
public class Demo03JDK9 {
public static void main(String[] args) throws IOException {
//1.创建一个字节输入流对象,构造方法中绑定要读取的数据源
FileInputStream fis = new FileInputStream("c:\\1.jpg");
//2.创建一个字节输出流对象,构造方法中绑定要写入的目的地
FileOutputStream fos = new FileOutputStream("d:\\1.jpg");
try(fis;fos){
//一次读取一个字节写入一个字节的方式
//3.使用字节输入流对象中的方法read读取文件
int len = 0;
while((len = fis.read())!=-1){
//4.使用字节输出流中的方法write,把读取到的字节写入到目的地的文件中
fos.write(len);
}
}catch (IOException e){
System.out.println(e);
}
//fos.write(1);//Stream Closed
}
}
第五章 属性集
5.1 概述
java.util.Properties
继承于Hashtable
,来表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,System.getProperties
方法就是返回一个Properties
对象。
5.2 Properties类
构造方法
-
public Properties()
:创建一个空的属性列表。基本的存储方法
-
public Object setProperty(String key, String value)
: 保存一对属性。 -
public String getProperty(String key)
:使用此属性列表中指定的键搜索属性值。 -
public Set<String> stringPropertyNames()
:所有键的名称的集合。
public class ProDemo {
public static void main(String[] args) throws FileNotFoundException {
// 创建属性集对象
Properties properties = new Properties();
// 添加键值对元素
properties.setProperty("filename", "a.txt");
properties.setProperty("length", "209385038");
properties.setProperty("location", "D:\\a.txt");
// 打印属性集对象
System.out.println(properties);
// 通过键,获取属性值
System.out.println(properties.getProperty("filename"));
System.out.println(properties.getProperty("length"));
System.out.println(properties.getProperty("location"));
// 遍历属性集,获取所有键的集合
Set<String> strings = properties.stringPropertyNames();
// 打印键值对
for (String key : strings ) {
System.out.println(key+" -- "+properties.getProperty(key));
}
}
}
输出结果:
{filename=a.txt, length=209385038, location=D:\a.txt}
a.txt
209385038
D:\a.txt
filename -- a.txt
length -- 209385038
location -- D:\a.txt
与流相关的方法
public void load(InputStream inStream)
: 从字节输入流中读取键值对。
参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就能够加载文本中的数据了。文本数据格式:
filename=a.txt
length=209385038
location=D:\a.txt
加载代码演示:
package com.itheima.demo07.Prop;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
/*
java.util.Properties集合 extends Hashtable<k,v> implements Map<k,v>
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。
Properties集合是一个唯一和IO流相结合的集合
可以使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
可以使用Properties集合中的方法load,把硬盘中保存的文件(键值对),读取到集合中使用
属性列表中每个键及其对应值都是一个字符串。
Properties集合是一个双列集合,key和value默认都是字符串
*/
public class Demo01Properties {
public static void main(String[] args) throws IOException {
show03();
}
/*
可以使用Properties集合中的方法load,把硬盘中保存的文件(键值对),读取到集合中使用
void load(InputStream inStream)
void load(Reader reader)
参数:
InputStream inStream:字节输入流,不能读取含有中文的键值对
Reader reader:字符输入流,能读取含有中文的键值对
使用步骤:
1.创建Properties集合对象
2.使用Properties集合对象中的方法load读取保存键值对的文件
3.遍历Properties集合
注意:
1.存储键值对的文件中,键与值默认的连接符号可以使用=,空格(其他符号)
2.存储键值对的文件中,可以使用#进行注释,被注释的键值对不会再被读取
3.存储键值对的文件中,键与值默认都是字符串,不用再加引号
*/
private static void show03() throws IOException {
//1.创建Properties集合对象
Properties prop = new Properties();
//2.使用Properties集合对象中的方法load读取保存键值对的文件
prop.load(new FileReader("09_IOAndProperties\\prop.txt"));
//prop.load(new FileInputStream("09_IOAndProperties\\prop.txt"));
//3.遍历Properties集合
Set<String> set = prop.stringPropertyNames();
for (String key : set) {
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}
/*
可以使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
void store(OutputStream out, String comments)
void store(Writer writer, String comments)
参数:
OutputStream out:字节输出流,不能写入中文
Writer writer:字符输出流,可以写中文
String comments:注释,用来解释说明保存的文件是做什么用的
不能使用中文,会产生乱码,默认是Unicode编码
一般使用""空字符串
使用步骤:
1.创建Properties集合对象,添加数据
2.创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
3.使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
4.释放资源
*/
private static void show02() throws IOException {
//1.创建Properties集合对象,添加数据
Properties prop = new Properties();
prop.setProperty("赵丽颖","168");
prop.setProperty("迪丽热巴","165");
prop.setProperty("古力娜扎","160");
//2.创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
//FileWriter fw = new FileWriter("09_IOAndProperties\\prop.txt");
//3.使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
//prop.store(fw,"save data");
//4.释放资源
//fw.close();
prop.store(new FileOutputStream("09_IOAndProperties\\prop2.txt"),"");
}
/*
使用Properties集合存储数据,遍历取出Properties集合中的数据
Properties集合是一个双列集合,key和value默认都是字符串
Properties集合有一些操作字符串的特有方法
Object setProperty(String key, String value) 调用 Hashtable 的方法 put。
String getProperty(String key) 通过key找到value值,此方法相当于Map集合中的get(key)方法
Set<String> stringPropertyNames() 返回此属性列表中的键集,其中该键及其对应值是字符串,此方法相当于Map集合中的keySet方法
*/
private static void show01() {
//创建Properties集合对象
Properties prop = new Properties();
//使用setProperty往集合中添加数据
prop.setProperty("赵丽颖","168");
prop.setProperty("迪丽热巴","165");
prop.setProperty("古力娜扎","160");
//prop.put(1,true);
//使用stringPropertyNames把Properties集合中的键取出,存储到一个Set集合中
Set<String> set = prop.stringPropertyNames();
//遍历Set集合,取出Properties集合的每一个键
for (String key : set) {
//使用getProperty方法通过key获取value
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}
}
小贴士:文本中的数据,必须是键值对形式,可以使用空格、等号、冒号等符号分隔。