IO流
一、文件
文件基础知识
文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文件,excel文件…都是文件。它既可以保存一张图片,也可以保持视频,声音。
文件流:
文件在程序中以流的形式来操作的
流:数据在数据源(文件)和程序(内存)之间经历的路径
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
创建文件
创建文件对象相关构造器和方法
- 相关方法
new File(String pathname)//根据路径构建一个File对象
new File(File parent,String child)//根据父目录文件+子路径构建
new File(String parent,String child)//根据父目录+子路径构建
createNewFile//创建新文件
2.获取文件信息(常用方法):
在utf-8下,一个英文字符是1个字节,一个汉字是3个字节
package com.hspedu.file;
import org.junit.jupiter.api.Test;
import java.io.File;
/**
* @author 韩顺平
* @version 1.0
*/
public class FileInformation {
public static void main(String[] args) {
}
//获取文件的信息
@Test
public void info() {
//先创建文件对象
File file = new File("e:\\news1.txt");
//调用相应的方法,得到对应信息
System.out.println("文件名字=" + file.getName());
//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
System.out.println("文件绝对路径=" + file.getAbsolutePath());
System.out.println("文件父级目录=" + file.getParent());
System.out.println("文件大小(字节)=" + file.length());
System.out.println("文件是否存在=" + file.exists());//T
System.out.println("是不是一个文件=" + file.isFile());//T
System.out.println("是不是一个目录=" + file.isDirectory());//F
}
}
目录操作
常见地文件操作
-
目录的操作和文件删除
mkdir创建一级目录,mkdirs创建多级目录,delete删除空目录或文件
在获取文件和目录过程中,还可以对文件和目录进行筛选(或者过滤):
import java.io.File; import java.io.FileFilter; public class Test { public static void main(String[] args) { File file = new File("D:\\java\\Java高级\\myfile"); // 判断是否是一个目录 if (file.isDirectory()) { File[] all = file.listFiles(new FileFilter() { @Override public boolean accept(File myfile) { // 判断是否是一个目录,是就通过 if (myfile.isDirectory()) { return true; } // 判断文件是否是以.txt结尾的,是就通过 if (myfile.getName().endsWith(".txt")) { return true; } return false; } }); for (int i = 0; i < all.length; i++) { System.out.println(all[i].getPath()); } } } }
二、Io流原理与分类
Java IO流原理
I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输。如读/写文件,网络通讯等。
Java程序中,对于数据的输入/输出操作以"流(stream)"的方式进行。
java.io包下提供了各种"流"类和接口,用以获取不同种类的数据,并通过方法输入或输出数据
输入input:读取外部数据(磁盘,光盘等存储设备的数据)到程序(内存)中。
输出output:将程序(内存)数据输出到磁盘,光盘等存储设备中
流的分类
按操作数据单位不同分为:字节流(8 bit),字符流(按字符)
按数据流的流向不同分为:输入流,输出流
按流的角色的不同分为:节点流,处理流/包装流
java中IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。
由这4个类派生出来的子类名称都是以其父类名为子类名后缀。比如声音等二进制文件,用字节流读取的话,可以无损操作,字符流可以用来处理文本文件,因为文本文件是用字符组织的
抽象类不能直接实例化,需要实例化它的对应的实现类。
- IO流体系图-常用的类
- IO流体系图
- 文件VS流
流和文件的关系
FileInputStream (字节输入流)
-
InputStream抽象类是所有类字节输入流的超类
-
InputStream常用的子类
- FileInputStream:文件输入流
- BufferedInputStream:缓存字节输入流
- ObjectInputStream:对象字节输入流
-
FileInputStream介绍
-
FileInputStream应用实例
-
创建FileInputStream对象,用read()方法读取文件数据
/* *单个字节读取,效率低 * ->使用read() */ @Test public void readFile01(){ String filePath = "c:\\hello.txt"; int readData=0; FileInputStream fileInputStream=null; try { //创建fileInputStream对象,用于读取文件 fileInputStream = new FileInputStream(filePath); //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止 //如果返回-1,表示读取完毕 while((readData=fileInputStream.read())!=-1){ System.out.print((char)readData); //打印是int转换为char显示 } //若打印汉字会出现乱码,一个汉字三个字节,而这是一个字节一个字节打印 } catch (IOException e) { e.printStackTrace(); }finally { //关闭文件流,释放资源 try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
2.创建FileInputStream对象,用read(byte[] b)方法读取文件
/* *使用read(byte[] b) */ @Test public void readFile02(){ String filePath = "c:\\hello.txt"; int readLen=0; //字节数组 byte[] buf = new byte[8];//一次读8个字节 FileInputStream fileInputStream=null; try { //创建fileInputStream对象,用于读取文件 fileInputStream = new FileInputStream(filePath); //从该输入流读取最多b,length字节的数据到字节数组。此方法将阻塞,直到某些输入可用 //如果返回-1,表示读取完毕 //如果读取正常,返回实际读取的字节数 while((readLen=fileInputStream.read(buf))!=-1){ System.out.print(new String(buf,0, readLen)); //打印是int转换为String显示 } //若打印汉字会出现乱码,一个汉字三个字节,而这是一个字节一个字节打印 } catch (IOException e) { e.printStackTrace(); }finally { //关闭文件流,释放资源 try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
-
FileOutputStream(字节输出流)
FileOutputStream应用实例
要求:请使用FileOutStream在a.txt文件,中写入"hello,world",如果文件不存在,会创建文件(注意:前提是目录已经存在)
public class FileOutputStream01 {
public static void main(String[] args) {
}
@Test
/*
* 演示使用FileOutStream 将数据写到文件中
* 如果文件不存在,则创建该文件
*/
public void writeFile(){
//创建FileOutStream对象
//说明
//1.new FileOutputStream(filePath)创建方式,当写入内容是,会覆盖原来内容
//2.new FileOutputStream(filePath,true)创建方式,当写入内容是,是追加到文件后面
String filePath="c:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
//得到FileOutputStream对象
fileOutputStream = new FileOutputStream(filePath,true);
//写人一个字节
// fileOutputStream.write('a');
//写入字符串
String str ="hello world";
//str.getBytes()可以把字符串->字节数组
// fileOutputStream.write(str.getBytes());
/*
write(byte[]b, int off,int len)将len字节从位于偏移量off的指定数组
*/
fileOutputStream.write(str.getBytes(),0,3);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件拷贝
思路分析
1创建文件输入流,将文件读入到程序
2 创建文件的输出流,将读取到的文件数据写入到指定位置
在完成程序时,应该是读取部分数据就写入到指定文件
package IO_Outputstream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
//完成文件拷贝,将c:\JAVA.jpg拷贝到C:\web\JAVA.jpg
//思路分析
//1. 创建文件的输入流,将文件读入到程序
//2. 创建文件的输出流,将读到的文件数据,写入到指定的文件
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
String srcFilePath = "c:\\JAVA.jpg";//定义输出路径
String destFilePath="C:\\web\\JAVA.jpg";//定义输入路径
try {
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream= new FileOutputStream(destFilePath);
//定义一个字节数组,提高读取效果
byte[] buf = new byte[1024];
int readlen=0;
while((readlen=fileInputStream.read(buf))!=-1)
{
//读取到后,就写入到文件 通过fileOutputStream
//即,一边读,一边写
fileOutputStream.write(buf,0,readlen);//一定要用这个方法,提高输出速度
}
System.out.println("拷贝成功");
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭输出流和输入流
if(fileInputStream!=null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if ((fileOutputStream!=null)){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
把关闭流放在finally里面保证一定会执行,并且是先关闭的输入流,然后关闭的输出流,注意关闭流的时候还执行了判空的操作 (我们采取的是先打开后关闭,后打开先关闭)
文件字符流说明
FileReader和FileWriter介绍
FileReader和FileWriter是字符输入输出流,即字符来操作io
FileReader相关方法:
new FileReader(File/String)
read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
read(char[]):批量读取多个字符到数组,返回读取到字符数,如果到文件末尾返回-1
相关API
new String(char[]):将char[]转换成String
new String(char[],off,len):将char[]的指定部分转换成String
————————————————
FileWriter常用方法
new FileWriter(File/String):覆盖模式,相当于流的指针在首端
new FileWriter(File/String,true):追加模式,相当于流的指针在尾端
write(int):写人单个字符
write(char[]):写入指定数组
write(char[],off,len):写入指定数组的指定部分
write(String):写入整个字符串
write(String,off,len):写入指定字符串的指定部分
相关 API: String类:toCharArray:将String转换为char[]
注意:
FileWriter使用后,必须关闭(close)或刷新(flush),否则写入不到指定文件
FileReader
-
FileReader和FileWriter
要求:
- 使用FileReader从story.txt读取内容,并显示
- 方法1,单个字符读取,用read()
- 使用FileReader从story.txt读取内容,并显示
/*
*单个字符读取文件
*/
@Test
public void readFile01(){
System.out.println("第二种");
String filePath="c:\\story.txt";
// 1.创建FileReader对象
FileReader fileReader = null;
int data=' ';
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();
}
}
}
}
代码解读:一个一个地读是可以处理中文字符的,不会出现字节读乱码情况
方法2,使用字符数组读取文件 read(buf)
/*
*字符数组读取文件
*/
@Test
public void readFile02(){
String filePath="c:\\story.txt";
// 1.创建FileReader对象
FileReader fileReader = null;
int readLen = 0;
char[] buf = new char[8];
try {
fileReader = new FileReader(filePath);
//循环读取 使用read,多个字符读取
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();
}
}
}
}
FileWriter
案例:使用FileWriter,注意细节
package I0_Writer;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriter_ {
public static void main(String[] args) {
String FilePath="c:\\note.txt";
//创建FileWriter对象
FileWriter filewriter = null;
char[] chars = {'a','b','c'};
try {
filewriter = new FileWriter(FilePath);
// 1. write(int):写人单个字符
filewriter.write('H');
// 2. write(char[]):写入指定数组
filewriter.write(chars);
// 3. write(char[],off,len):写入指定数组的指定部分
filewriter.write("琳琳我".toCharArray(),0,3);
// 4. write(String):写入整个字符串
filewriter.write("风雨之后见彩虹");
filewriter.write(" 你好北京");
// 5. write(String,off,len):写入指定字符串的指定部分
filewriter.write("上海北京",0,2);
//在数据量大的情况下,用循环操作
} catch (IOException e) {
e.printStackTrace();
}finally{
//对于FileWriter,一定要关闭流,或者flush才能正在的把数据写入到文件
try {
// filewriter.flush();
//close等于fulsh()+关闭
filewriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、节点流和处理流
1 基本介绍
处理流例如BufferedWriter类中,有属性Writer,既可以封装一个节点流,该节点流可以是任意的,只要是Writer子类。
2.处理流设计模型
节点流和处理流的区别和联系
节点流是底层流,低级流,直接跟数据源相接
处理流(包装流)包装节点流,即可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出(源码理解)
处理流也叫包装流对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连(模拟修饰器设计模式)
处理流的功能主要体现在以下两个方面
性能的提高:主要以增加缓冲的方式来提高输入输出的效率
操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便
3.BufferedReader
BufferedReader和BufferedWriter属于字符流,是按照字符读取数据的,所以最好处理文本文件,想图片,声音这种字节组织的二进制文件的话,用字符流读取可能会造成文件损失,所以最好使用字节流
- 应用案例
- 使用BufferedReader读取文本文件,并显示在控制台
package IO_reader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/*
演示bufferedreader应用
*/
public class BufferedReader_ {
public static void main(String[] args) throws IOException {
String filePath="c:\\ab.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,因为底层会自动的去关闭节点流
bufferedReader.close();
}
}
***注意:***BufferedReader和BufferedWriter属于字符流,是按照字符来读取数据的,关闭时,只需要关闭外层流即可。【因为底层会调用的处理流传入的字节流的close方法】
4.BufferedWriter
public class BufferedWrite1 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String filePath="e:\\ok.txt";
//创建BufferWritered
//说明
//1. new FileWriter(filePath,true) 表示以追加的方式写人
//2.new FileWriter(filePath) 表示以覆盖的方式写入
new BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
//new BufferedWriter
bufferedWriter.write("hello, 韩顺的");
bufferedWriter.newLine();//插入一个和系统相关的换行
bufferedWriter.write("hello, 韩顺的");
bufferedWriter.newLine();//插入一个和系统相关的换行
bufferedWriter.write("hello, 韩顺的");
//说明:关闭外层流即可,传入的 new FileWriter(filePath),会在底层流关闭
bufferedWriter.close();
}
}
5.对象处理流
专门用来处理对象的
- 基本介绍
- 功能:提供了对基本类型或者对象类型的序列化和反序列化的方法
- ObjectOutputStream提供序列化功能
- ObjectInputStream提供反序列功能
(1)ObjectOutputStream
- 应用案例
- 使用ObjectOutputStream序列化基本数据类型和一个Dog对象(name,age),并保存到data.dat
package IO_Inputstream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/*
演示ObjectOutputStream的使用,完成数据的序列化
*/
public class ObjectOutputStream_ {
public static void main(String[] args) throws IOException {
//序列化后,保存的文件格式,不是纯文本而是按照他的格式来保存
String filePath="c:\\data.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到c:\\data.dat
oos.write(100);//int->Integer(实现了Serialzable)
oos.writeBoolean(true);//boolean->Boolean(实现了Serialzable)
oos.writeChar('a');//char->Character (实现了Serialzable)
oos.writeDouble(9.5);//double->Double(实现了Serialzable)
oos.writeUTF("xxx");//String(实现了Serialzable)
//保存一个dog对象
oos.writeObject(new dog("旺财",12));
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;
}
}
因为序列化后的文件不是纯文本,所以看不清楚的
(2)ObjectInputStream
- 应用案例
- 使用ObjectInputStream读取data.dat并反序列化恢复数据
package IO_Inputstream;
import IO_Outputstream.dog;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectInputStream_ {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//序列化后,保存的文件格式,不是纯文本而是按照他的格式来保存
String filePath="c:\\data.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);//底层object->Dog
//特别重要的细节
//1.如果我们希望调用Dog的方法,需要向下转型
//2.需要我们将Dog类的定义,拷贝到可以引用的位置
dog dog2 = (dog) dog;
System.out.println(dog2.getName());
//关闭流,关闭外层流即可
ois.close();
}
}
(3)对象处理流使用细节
注意事项和细节说明
读写顺序要一致
要求实现序列化或反序列化对象,需要实现Serializable
序列化的类中建议添加SerialVersionUID,为了提高版本兼容性
序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
序列化对象时,要求里面属性的类型也需要实现序列化接口
序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也默认实现了序列化
(4)判断读到最后一个
对象流操作的是对象,存入一个一个的对象,也只能读一个一个的对象,但是存在一个问题就是写入多少个就只能读多少个,没有读取到结尾的判断方法,如果读取超过了则会抛出异常java.io.EOFException,那咱们想做到通用如何来判断是否是最后一个呢?
1.在存入对象的时候使用集合的方式来存储对象,这样在获取时就只需要获取集合,然后遍历集合即可.
这种是将本来的多个对象转化为一个集合对象,再从集合对象中去获取数据
2.方式一的方式可以说是比较好的解决方案,如果不想转为集合对象也可以在存入对象前或者后面加一个标志,可以在第一位置加一个int类型的值来记录存入的对象个数,也可以在最后加入一个null来做结束标识.
3.使用异常处理方式,这个很简单,直接处理 EOFException 就行了,当遇到EOFException 时表示已经读到末尾了.
6.转换流
1 介绍
(1)InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成(转换)Reader(字符流);
(2)OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流);
(3)当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换为字符流;
(4)可以在使用时指定编码格式(比如utf-8、gbk、gb2312、ISO8859-1等)。
2 应用实例
如果文本文件的类型和编程软件设置的编码不一致会出现乱码的情况。
public class CodeQuestion {
public static void main(String[] args) throws IOException {
//读取e:\\a.txt 文件到程序
//思路
//1. 创建字符输入流 BufferedReader [处理流]
//2. 使用 BufferedReader 对象读取a.txt
//3. 默认情况下,读取文件是按照 utf-8 编码
String filePath = "e:\\a.txt";
BufferedReader br = new BufferedReader(new FileReader(filePath));
String s = br.readLine();
System.out.println("读取到的内容: " + s);
br.close();
//InputStreamReader
//OutputStreamWriter
}
}
ANSI码是国标码,对应系统就是GBK码,国标码是一个统称,每个国家有自己的国标码,国标码是根据你的系统来确定的出现乱码是因为没有指定读取的编码方式,转换流可以把字节流转换成字符流,字节流是可以指定编码方式的
为了达到最高的效率,避免频繁地进行字符与字节间的相互转换,最好不要直接使用这两个类来进行读写,应尽量使用BufferedWriter类包装OutputStreamWriter类,用BufferedReader类包装InputStreamReader类。例如:
BufferedWriterout = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReaderin = new BufferedReader(new InputStreamReader(System.in));
接着从一个实际的应用中来了解InputStreamReader的作用,用一种简单的方式读取键盘上输入的一行字符:
BufferedReader in = newBufferedReader(new InputStreamReader(System.in));
String strLine =in.readLine();
可见,构建BufferedReader对象时,必须传递一个Reader类型的对象作为参数,而键盘对应的System.in是一个InputStream 类型的对象,所以这里需要用到一个InputStreamReader的转换类,将System.in转换成字符流之后,放入到字符流缓冲区之中,之后从缓冲区中每次读入一行数据;
InputStreamReader
应用案例
- 编码将字节流FileInputStream包装成字符流InputStreamReader,对文件进行读取按照utf-8格式,进而在包装成BufferedReader
package transformation;
import java.io.*;
/*
*演示使用InputStreamReader 转换流解决中文乱码问题
* 将字节流FileInputStream 转换成字符流InputStreamReader,指定编码gbk/utf-8
*/
public class InputStreamReader_ {
public static void main(String[] args) throws IOException {
String filePath="c:\\a.txt";
//1.把FileInputStream转成 InputStreamReader
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath),"gbk");
//3.把InputStreamReader传入BufferedReader
//BufferedReader br = new BufferedReader(isr);
//将2和3合在一起
BufferedReader br = new BufferedReader(new InputStreamReader
new FileInputStream(filePath),"gbk"));
//4.读取
String s = br.readLine();
System.out.println("读取内容="+s);
//5.关闭外层流
br.close();
}
}
OutputStreamWriter
- 应用案例
- 编程将字节流FileOutputStream包装成字符流OutputStreamWriter,对文件进行写入按照gbk
package transformation;
import java.io.*;
public class OutputStreamWriter_ {
public static void main(String[] args) throws IOException {
String filePath="c:\\a.txt";
String charset="gbk";
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),charset);
osw.write("问进ie");
osw.close();
System.out.println("按照"+charset+"保存文件成功");
}
}
四、标准输入输出流
标准输入输出流
package standard;
public class InputAndOutput {
public static void main(String[] args) {
//System类的public final static InputStream in = null;
//System.in 编译类型 InputStream
//System.in 运行类型 BufferedInputStream
//表示的是标准输入 键盘
System.out.println(System.in.getClass());
//1.System.out public final static Printstream out = null;
//2.编译类型 PrintStream
//3.运行类型PrintStream
//4.表示标准输出 显示器
System.out.println(System.out.getClass());
}
}
五、 打印流
1 PrintStream(字节打印流)
打印流只有输出流没有输入流
/**
* 演示PrintStream (字节打印流/输出流)
*/
public class PrintStream_ {
public static void main(String[] args) throws IOException {
PrintStream out = System.out;
//在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
/*
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
*/
out.print("john, hello");
//因为print底层使用的是write , 所以我们可以直接调用write进行打印/输出
out.write("韩顺平,你好".getBytes());
out.close();
//我们可以去修改打印流输出的位置/设备
//1. 输出修改成到 "e:\\f1.txt"
//2. "hello, 韩顺平教育~" 就会输出到 e:\f1.txt
//3. public static void setOut(PrintStream out) {
// checkIO();
// setOut0(out); // native 方法,修改了out
// }
System.setOut(new PrintStream("e:\\f1.txt"));
System.out.println("hello, 韩顺平教育~");
}
}
2 PrintWriter(字符打印流)
public class PrintWriter_ {
public static void main(String[] args) throws IOException {
//PrintWriter printWriter = new PrintWriter(System.out);
PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
printWriter.print("hi, 北京你好~~~~");
printWriter.close();//flush + 关闭流, 才会将数据写入到文件..
}
}
六、Properties类
1 基本介绍
(1)专门用于读写配置文件的集合类
配置文件的格式:
键=值
(2)注意事项
键值对不需要有空格,值不需要用引号一起来,默认类型是String。
(3)Properties的常见方法
① load:加载配置文件的键值对到Properties对象;
② list:将数据显示到指定设备;
③ getProperty(key):根据键获取值;
④ setProperty(key,value):设置键值对到Properties对象【没有就是新建,有就是修改】;
⑤ store:将Properties中的键值对存储到配置文件中,在IDEA中,保存信息到配置文件,如果含有中文,会存储为unicode码。
2 应用实例
(1)传统方法
在src目录下创建mysql.properties配置文件,里面的内容:
public class Properties01 {
public static void main(String[] args) throws IOException {
//读取mysql.properties 文件,并得到ip, user 和 pwd
BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
String line = "";
while ((line = br.readLine()) != null) { //循环读取
String[] split = line.split("=");
//如果我们要求指定的ip值
if("ip".equals(split[0])) {
System.out.println(split[0] + "值是: " + split[1]);
}
}
br.close();
}
}
(2)properties类方法
public class Properties02 {
public static void main(String[] args) throws IOException {
//使用Properties 类来读取mysql.properties 文件
//1. 创建Properties 对象
Properties properties = new Properties();
//2. 加载指定配置文件
properties.load(new FileReader("src\\mysql.properties"));
//3. 把k-v显示控制台
properties.list(System.out);
//4. 根据key 获取对应的值
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println("用户名=" + user);
System.out.println("密码是=" + pwd);
}
}
public class Properties03 {
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;//如果key 存在,就替换
return old;
}
}
addEntry(hash, key, value, index);//如果是新k, 就addEntry
return null;
}
*/
properties.setProperty("charset", "utf8");
properties.setProperty("user", "汤姆");//注意保存时,是中文的 unicode码值
properties.setProperty("pwd", "888888");
//将k-v 存储文件中即可
//注意null是指properties配置文件没有要说明的注释,如果有的话会在配置文件的
//最上方显示。
properties.store(new FileOutputStream("src\\mysql2.properties"), null);
System.out.println("保存配置文件成功~");
}
}
七、内存流
1.1 什么是内存流
当输出流的目的,和输入流的源是内存时,这样的流称之为内存流。
ByteArrayOutputStream:内存流的输出流
ByteArrayInputStream:内存流的输入流,它是唯一一种能够直接从网络上获取二进制数据的流
CharArrayReader:内存流中的输入流
CharArrayWriter:内存流中的输出流
ByteArrayInputStream主要完成将内容从内存读入程序之中,而ByteArrayOutputStream的功能主要是将数据写入到内存中。
不是只有程序的文件到程序的流 还有内存到内存的流