目录
19.4.8FileReader和FileWriter应用案例
19.5.5处理流-BufferedReader和BufferedWriter
19.5.6处理流-BufferedInputStream和BufferedOutputStream
19.5.8对象流-ObjectInputSream和ObjectOutputStream
19.5.11转换流-InputStreamReader和OutputStreamWriter
19.6打印流-PrintStream和PrintWriter
19.1文件
19.1.1什么是文件
文件对于我们来说并不陌生,文件是保存数据的地方,比如word文档、txt文档、excel文件...
19.1.2文件流
19.2常用的文件操作
19.2.1创建文件对象相关构造器和方法
package Ex1;
import java.io.*;
import java.io.IOException;
/*在d盘下创建文件,news1.txt,news2.txt,news3.txt使用三种不同方式创建------成功*/
public class FileCreate {
public static void main(String[] args) {
// TODO Auto-generated method stub
create01();
create02();
create03();
}
//方式一通过路径构建file对象
// new File(String pathname);
public static void create01(){
String filePath = "d:\\news1.txt"; //获取路径
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件1创建成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//方式二根据父目录文件+子路径构建
//new File(File parent,String child)
public static void create02() {
File parentFile = new File("d:\\");
String fileName = "news2.txt";
//只有执行了createNewFile方法,才会真正的在磁盘创建该文件
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件2创建成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//方式三根据父目录+子路径构建
//new File(String parent,String child)
public static void create03() {
String parentPath = "d:\\";
String fileName = "news3.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("文件3创建成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//下面四个都是抽象类
//InputStream输入字节流
//OutputStream输出字节流
//Reader读字符流操作
//Writer写字符流
19.2.2获取文件的相关信息
19.2.3应用案例
package Ex2;
/*获取文件信息*/
import java.io.*;
@SuppressWarnings("unused")
public class FileInformation {
public static void main(String[] args) {
// TODO Auto-generated method stub
info();
}
//获取文件信息
public static void info() {
//先创建文件对象
File file = new File("d:\\news2.txt");
//调用相应的方法,得到对应信息
System.out.println("文件名字="+file.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());
System.out.println("是不是一个标准文件="+file.isFile());
System.out.println("是不是一个目录="+file.isDirectory());
/*
文件名字=news2.txt
文件绝对路径:d:\news2.txt
文件父级目录:d:\
文件大小(字节)=0
文件是否存在:true
是不是一个标准文件=true
是不是一个目录=false
*/
}
}
19.2.4目录的操作和文件删除
package Ex2;
import java.io.*;
public class Exdemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
createDirectory();//目录创建成功
}
public static void createDirectory() {
File file = new File("d:\\e");
if(!file.exists()) {
//创建多级目录mkdirs,如果创建单级目录使用即可mkdir(mkdirs也行)
if(file.mkdirs()) {
System.out.println("目录创建成功");
}
} else {
System.out.println("创建失败");
}
}
}
19.2.5应用案例
package Ex2;
import java.io.*;
//判断d:\\news3是否存在,存在就删除
public class Directory {
public static void main(String[] args) {
// TODO Auto-generated method stub
delete(); //删除成功
}
public static void delete() {
File file = new File("d:\\news3.txt");
if(file.exists()) {
if(file.delete()) {
System.out.println("删除成功");
}
} else {
System.out.println("该文件不存在");
}
}
}
19.3 IO流原理及流的分类
19.3.1Java IO流原理
19.3.2流的分类
19.4 IO流体系图-常用的类
1、IO流体系图
2、文件VS流
19.4.1FileInputStream介绍
19.4.2应用案例
要求:请使用FileInputStream读取hello.txt文件,并将文件内容显示到控制台
package FileInputStream;
/*读取hello.txt文件,并输出到控制台*/
import java.io.*;
public class FileInputStream01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
readFile01();//123hello
readFile02();//123hello
}
//演示读取文件,单个字节读取(效率较低),使用ready(byte[] b)
public static void readFile01() {
String filePath = "d:\\hello.txt"; //设置路径
int readData = 0; //用来获取读到的字节
FileInputStream fileInputStream = null;
try {
//创建FileInputStream对象,用于读取文件
fileInputStream = new FileInputStream(filePath);
//从输入流读取一个字节的数据。.read获取当前字节
//如果返回-1,表示读取完毕
while((readData = fileInputStream.read())!=-1) { //读取字节赋值给readData,再与-1比较
System.out.print((char)readData);//转成char显示
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//使用read(byte[] b) 读取文件,提高效率
public static void readFile02() {
String filePath = "d:\\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.println(new String(buf,0,readLen));//显示
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
19.4.3FileOutputStream介绍
19.4.4FileOutputSream应用案例
要求:请使用FileOutputStream在a.txt文件,中写入"hello,world".
[注:如果文件不存在,会创建文件]
package Ex1;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//使用FileOutputStream在b.txt中写入hello,world
public class FileOutputStream01 {
public static void main(String[] args) {
writeFile();
System.out.println("成功");
}
/*如果该文件不存在,则会自动创建该文件
* */
public static void writeFile(){
//创建FileOutputStream对象
String filePath = "d:/c.txt";
FileOutputStream fileOutputStream = null;
try {
//创建对象
//说明:new FileOutputStream(filePath,true)创建方式,是追加到文件后面
//默认是flase,覆盖
fileOutputStream = new FileOutputStream(filePath);
//写入数据
//1、写入一个字节
// fileOutputStream.write("H");
//2、写入一个字符串
String str = "lh,world";
//str.getBytes(),可以把字符串转成->字节数组
//fileOutputStream.write(str.getBytes());
fileOutputStream.write(str.getBytes(),0,str.getBytes().length);//
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileOutputStream!=null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
案例二:要求编程完成图片/音乐的拷贝
package Ex1;
import java.io.*;
//照片视频的copy
public class FileCopy {
public static void main(String[] args) {
//完成文件的拷贝,将d:/yellowDog.jpg--拷贝到d:/yellowDog02.jpg
/*思路:
*1、创建文件的输入流,将文件读入到程序
*2、创建文件输出流,将读取到的文件数据,写入到指定的文件
* */
FileInputStream fr = null;
FileOutputStream fw = null;
String frpath = "d:/yellowDog.jpg";//读取文件路径
String fwpath = "d:/yellowDog02.jpg";//存写文件路径
try {
fw = new FileOutputStream(fwpath);
fr = new FileInputStream(frpath);
//因为是字节流,定义一个字节数组,提高读取效率
byte[] buf = new byte[1024];
int readLen=0; //接收读取到的字节数
while((readLen = fr.read(buf))!=-1){
fw.write(buf,0,readLen);
}
System.out.println("Copy成功");//Copy成功
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fr!=null) {
fr.close();
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
19.4.5FileReader和FileWriter介绍
19.4.6FileReader相关方法
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
19.4.7FileWriter常用方法
19.4.8FileReader和FileWriter应用案例
要求:1、使用FileReader从story.txt文件,读取内容。并显示
package Ex2;
//记得关闭流!!!
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
//使用FileReader读取d:/c.txt的内容,显示在控制台
public class FileReader01 {
public static void main(String[] args) {
readFile();//字符读取文件---結束
readFile02();//字符数组读取文件---成功
}
public static void readFile(){
//单个字符读取文件
String filePath = "d:/c.txt";
FileReader fr = null;
int data = 0;//接收读取的字符
try {
//创建FileReader对象
fr = new FileReader(filePath);
//循环读取。read,单个字符读取
while((data = fr.read())!=-1){
System.out.print((char)data);
}
System.out.println();
System.out.println("结束");//成功
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fr!=null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void readFile02(){
System.out.println("字符数组读取");
String filePath="d:/b.txt";
FileReader fileReader = null;
int readLen=0;//接收读取的字符数
char[] buf = new char[8];//一次性读取8个字符
try {
//创建对象
fileReader = new FileReader(filePath);
//循环读取
while((readLen = fileReader.read(buf))!=-1){
System.out.print(new String(buf,0,readLen));//new String(char[],off,len),将char[]的指定部分转化成String
System.out.println();
}
System.out.println("成功");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fileReader!=null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、使用FileWriter将"风雨之后,定见彩虹",写入到note.txt文件中
package Ex2;
import java.io.FileWriter;
import java.io.IOException;
//将"风雨之后,定见彩虹",写入到d:/note.txt文件中=====成功
public class FileWriter01 {
public static void main(String[] args) {
String filePath = "d:/note.txt";
FileWriter fw = null;
try {
//创建对象
fw = new FileWriter(filePath);
//写入数据
fw.write("风雨之后,定见彩虹~!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fw!=null) {
//对应FileWritet,一定要关闭流,护着flush才能把数据写入到文件
fw.close(); //关闭流,等价于flush()+关闭
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("写入成功!");
}
}
19.5 节点流和处理流
19.5.1基本介绍
19.5.2节点流和处理流一览图
19.5.3节点流和处理流的区别和联系
1、节点流是底层流/低级流,直接跟数据源相接
2、处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。
3、处理流(也叫包装流)对节点进行包装,使用修饰器设计模式,不会直接与数据源相连
19.5.4处理流的功能主要体现在以下两个方面
1、性能的提高:主要以增加缓冲的方式提高输入输出的效率
2、操作的便捷:处理流提供一系列便捷的方法
19.5.5处理流-BufferedReader和BufferedWriter
应用案例1:使用BufferedReader读取文本文件,并显示在控制台
package Ex3;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
//读取d:/note.txt文件,并显示在控制台
public class BufferedReader_01 {
public static void main(String[] args) throws IOException {
String filePath = "d:/note.txt";
//创建对象
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
//读取
String line;//接读取返回的字符串
//1、bufferedReader.readLine()按行读取,返回读取的字符串
//2、当返回null时,表示文件读取完毕
while((line = bufferedReader.readLine())!=null){
System.out.println(line);
}
System.out.println("成功,结束");
bufferedReader.close();
}
}
应用案例2:使用BufferedWriter将数据写入文件中
package Ex3;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
//将“hello,IO”写入到文件d:\note.txt中
public class BufferedWriter_02 {
public static void main(String[] args) throws IOException {
String filePath = "d:/note.txt";
//创建对象
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath,true));//这里是追加!!!
//写入数据
bw.newLine();
bw.write("hellw,IO");
bw.newLine();//插入一个和系统相关的换行,另起一行
bw.write("hello2,io");
bw.newLine();
bw.write("hello3,io");
System.out.println("写入成功");
//关闭流
bw.close();
}
}
19.5.6处理流-BufferedInputStream和BufferedOutputStream
19.5.7介绍BufferedOutputSream
19.5.8对象流-ObjectInputSream和ObjectOutputStream
19.5.9对象流介绍
19.5.10标准输入输出流
19.5.11转换流-InputStreamReader和OutputStreamWriter
19.6打印流-PrintStream和PrintWriter
19.7Properties类
19.7.1看一个需求
1、传统方法实现
package Properties;
/*如何读取ip、user、pwd的值,如一个配置文件 mysql.properties
* ip=192.168.43.195
* user=root
* pwd=123
* 传统方法:
* */
import java.io.*;
public class Properties01 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//读取mysql.properties文件,并得到ip,user,pwd
BufferedReader br = new BufferedReader(new FileReader("d:\\mysql2.properties"));
String line=null;
while((line = br.readLine())!=null) {//循环读取
String[] split= line.split("="); //以=分割
//获取指定的ip值
if("pwd".equals(split[0])) {
System.out.println(split[0]+"值为:"+split[1]);
}
}
br.close();
}
}
2、使用Properties类
读取
package Properties;
import java.io.*;
import java.util.*;
public class Properties02 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
//使用Properties类来创建 配置文件,修改配置文件的内容
Properties properties = new Properties();
//创建,如果该文件有key,就是创建;反之,修改。
properties.setProperty("charset", "utf8");
properties.setProperty("user", "汤姆");//如果是中文,则保存的unicode码值
properties.setProperty("pwd", "666");
//将k-v存储文件即可
properties.store(new FileOutputStream("d:\\mysql2.properties"), "helloword");//第二参数为注释
System.out.println("配置文件成功");
}
}
修改
package Properties;
import java.io.*;
import java.util.*;
public class Properties02 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
//使用Properties类来创建 配置文件,修改配置文件的内容
Properties properties = new Properties();
//创建,如果该文件有key,就是创建;反之,修改。
properties.setProperty("charset", "utf8");
properties.setProperty("user", "汤姆");//如果是中文,则保存的unicode码值
properties.setProperty("pwd", "666");
//将k-v存储文件即可
properties.store(new FileOutputStream("d:\\mysql2.properties"), "helloword");//第二参数为注释
System.out.println("配置文件成功");
}
}
19.7.2基本介绍
1、专门用于读写配置文件的集合类
配置文件格式: 键 = 值
2、注意:键值对不需要有空格,值不需要用引号。默认类型为String
3、Properties的常见方法: