1. File类的使用
- File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
- File类声明在java.io包下
- File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
- 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点"
1.1 如何创建File类的实例
四种方法创建(先讲3种):(三种方法都比较常用)
File(String filePath)
File(String parentPath, String childPath)
File(File parentFile, String childPath)
//这里都没有考虑在硬盘中真实存在这样的文件,它们都只是内存层面的几个对象而已
//toString()方法只是将文件的路径进行输出
//方式1:
File(String filePath);
File file1 = new File("hello.txt");
File file2 = new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt");
System.out.println(file1);
System.out.println(file2);
//方式2:
File(String parentPath,String childPath)
File file3 = new File("D:\\workspace_idea1","JavaSenior");
System.out.println(file3);
//方式3:
File(File parentFile,String childPath)
File file4 = new File(file3,"hi.txt");
System.out.println(file4);
1.2 相对路径和绝对路径
相对路径:相较于某个路径下,指明的路径
绝对路径:包含盘符在内的文件或文件目录的路径
注:双杠\\:目的不让编译器识别为转义字符
说明:
IDEA中:如果大家开发使用JUnit中的单元测试方法测试,相对路径即为当前的Module下
如果是使用main()测试,相对路径即为当前的Project下
Eclipse中:不管使用单元测试方法还是使用main()测试,相对路径都是当前的Project下
@Test
public void test1(){
File file1 = new File("hello.txt");//相当于当前module
File file2 = new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt");
}
1.3 关于路径分隔符的问题:
Windows:\\
UNIX: /
由于Java跨平台特性,因此开发可以使用File.separator来替代分隔符位置
1.4 File类的常用方法
1.4.1 File类的获取功能
注:此时的方法也针对的是内存,不管硬盘中实际是否有此文件
关于相对路径getParent()将会返回null [无论硬盘是否存在该文件]
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
public long lastModified() :获取最后一次的修改时间,毫秒值
//如下两种方法适用于文件目录
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
1.4.2 File类 的重命名功能
public boolean renameTo(File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)为例:
要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在
@Test
public void test4(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\io\\hi.txt");
boolean renameTo = file2.renameTo(file1);
System.out.println(renameTo);
}
1.4.3 File类 的判断功能
public boolean isDirectory():判断是否是文件目录
public boolean isFile() :判断是否是文件
public boolean exists() :判断是否存在
public boolean canRead() :判断是否可读
public boolean canWrite() :判断是否可写
public boolean isHidden() :判断是否隐藏
1.4.4 File类的创建功能
创建硬盘中对应的文件/文件目录:
public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。 如果此文件目录的上层目录不存在,也不创建。
public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
注意事项:如果你创建文件或者文件目录没有写盘符路径,那么,默认在项目路径下。
@Test
public void test6() throws IOException{
//文件的创建
File file1 = new File("hi.txt");
if(!file1.exists()){
file1.createNewFile();
System.out.println("创建成功");
}else{//文件存在
file1.delete();
System.out.println("删除成功");
}
}
//文件目录的创建
@Test
public void test1(){
File file1 = new File("d:\\io\\io1\\io3");
boolean mkdir = file1.mkdir();
if(mkdir){
System.out.println("创建成功1");
}
File file2 = new File("d:\\io\\io1\\io4");
boolean mkdir1 = file2.mkdirs();
if(mkdir1){
System.out.println("创建成功2");
}
}
1.4.5 File类的删除功能
删除文件中对应的文件/文件目录:
public boolean delete():删除文件或者文件夹删除
注意事项: Java中的删除不走回收站。 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
1.4.6 两个练习
@Test
public void test(){
File file1 = new File("D:\\work");
String[] list = file1.list();
for(String s:list){
if(s.endWith(.jpg)){
System.out.println(s);
}
}
}
//遍历制定目录所有文件名称,包括子文件目录中的文件
@Test
public void test(){
//方法1:递归调用
//创建文件目录的对象
File dir = new File("D:\\teach\\01_javaSE\\尚硅谷Java编程语言\\3软件");
//打印文件目录的文件
printAllFiles(dir);
}
public void printAllFiles(File file){
//打印目录的子文件
File[] subfiles = file.listFiles();
for(File f:subfiles){
if(f.isDirectory){
printAllFiles(f);
}else{//文件,直接打印
System.out.println(f);
}
}
}
//拓展1:求指定目录所在空间的大小
public long getDirectorySize(File file){
//如果file是文件,直接返回file.length
//如果file是目录,把它的下一级的所有大小加起来就是它的总大小
long size = 0;
if(file.isFile()){
size += file.length();
}else{
File[] all = file.listFiles();//获取file的下一项
//累加all[i]的大小
for(File f:all){
size += getDirectorySize(f);
}
}
return size;
}
//拓展2:删除指定的目录
public void deleteDirectory(File file){
//如果file是文件,直接delete
//如果file是目录,先把它的下一级文件层层删除,在删除自己
if(file.isDirectory()){
File[] all = file.listFiles();
//循环删除每一项
for(File f:all){
deleteDirectory(f);
}
}
file.delete();//最后删除自己:当下级没有文件时
}
2. IO流原理及流的分类
Tips:Google I/O 寓为"在开放中创新" (Innovatio in the Open)
Input/Output 二进制 1/0
2.1 Java IO原理
- I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等
- Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行
- java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据
2.2 流的分类
按数据流向不同划分(站在内存角度考虑):
输入流:数据 ---> 程序 (读数据)
输出流:程序 ---> 数据 (写数据)
按流中处理数据基本单位划分:
字节流:以一个一个Byte为基本单位
字符流:以一个一个char为基本单位
按流是否直接作用于文件:
节点流:流直接作用在文件上,文件加载到内存,直接构造一个流,将此文件传输到内存中
处理流:流是作用在已有的流的基础之上的,在节点流的外面又套了一些东西--->比方说让流传输加快的手段
2.3 流的体系结构
蓝框的流需要着重记住:
垃圾回收机制只回收JVM堆内存里的对象空间
对其他物理连接:比如数据库连接、输入流输出流、Socket连接无能为力
抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
InputStream FileInputStream BufferedInputStream
OutputStream FileOutputStream BufferedOutputStream
Reader FileReader BufferedReader
Writer FileWriter BufferedWriter
FileInputStream :(read(byte[ ] buffer))
FileOutputStream :(write(byte[ ] buffer,0,len))
FileReader:(read(char[ ] cbuf))
FileWriter :(write(char[] cbuf,0,len))
BufferedInputStream :(read(byte[ ] buffer))
BufferedOutputStream:(write(byte[ ] buffer,0,len))/flush()
BufferedReader:(read(char[ ] cbuf) / readLine())
BufferedWriter:(write(char[] cbuf,0,len))/ flush()
注:readLine()后无换行符,若要保证和原文件的一致性,需要根据需要添加换行符
//方法1:
bw.write(data + "\n");//data中不包含换行符//方法2:
bw.write(data);//data中不包含换行符
bw.newLine();//提供换行的操作flush() : 对于处理流来说,一般都有缓存区。而flush每当调用它,内存中的数据都被写出去了,如果有缓存区但没自己调用flush(),需要手动调用此方法。
2.3.1 FileReader
说明点:
- read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
- 异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理
- 读入的文件一定要存在,否则就会报FileNotFoundException
//将day09下的hello.txt文件内容读入程序中,并输出到控制台
@Test
public void testFileReader(){
FileReader fr = null;
try{
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前module
//2.提供具体的流,相当于造了一个管道,直接对文件造
fr = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符。如果达到文件末尾,返回-1
int data = fr.read();
while(data != -1){
System.out.print((char)data);
data = fr.read();
}
//方式2:
int data;
while((data = fr.read()) != -1){
System.out.print((char)data);
}
}catch(IOException e){
e.printStackTrace();
}finally{
//4.流的关闭操作
try{
if(fr != null)
fr.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
@Test
public void testFileReader(){
FileReader fr = null;
try{
//1.File类的实例化
File file = new File("hello.txt");//相较于当前module
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
char[] cbuf = new char[5];
int len;
while((len = fr.read(cbuf))!= -1){
//方式一:
//正确的写法:
for(int i = 0;i < len;i++){
System.out.println(cbuf[i]);
}
//错误的写法:
for(int i = 0;i < cubf.length;i++){
System.out.println(cbuf[i]);
}
//方式二:
//正确的写法:
String str = new String(cbuf,0,len);
//错误的写法:对应着方式一错误的写法
String str = new String(cbuf);
System.out.print(str);
}
}catch(IOException e){
e.printStackTrace();
}finally{
//4.流的关闭操作
try{
if(fr != null)
fr.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
2.3.2 FileWriter
说明:
- 输出操作,对应的File可以不存在的,并不会报异常
File对应的硬盘中的文件如果不存在,在输出过程中,会自动创建此文件
File对应的硬盘中的文件如果存在:
如果流使用的构造器是:FileWriter(file,false)/FileWriter(file):对原有文件的覆盖
如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
@Test
public void testFileWriter() throws IOException{
//1.提供File类的对象,指明写出到的文件
File file = new File("hello1.txt");
//2.提供FileWriter的对象,用于数据的写出
FileWriter fw = new FileWriter(file);
FileWriter fw1 = new FileWriter(file,append:true);//表示不会覆盖原文件,在源文件基础上添加
//3.写出的操作
fw.write("I have a dream\n");
fw.write("you need to have a dream!");
//4.流资源的关闭
fw.close();
}
两者结合(FileReader 和 FileWriter)实例:
@Test
public void testFileReaderWriter(){
FileReader fr = null;
FileWriter fw = null;
try{
//1.创建File类的对象,指明读入和写出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello2.txt");
//不能使用字符流来处理图片等字节数据
File srcFile = new File("happy.jpg");
File destFile = new File("happy1.jpg");
//2.创建输入流和输出流的对象
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;//记录每次读入到cbuf数组中字符的个数
while((len = fr.read(cbuf)) != -1){
//每次写出len个字符
fw.write(cbuf,0,len);
}
} catch(IOException e){
e.printStackTrace();
}finally{
//4.关闭流资源
try{
if(fw != null)
fw.close();
}catch(IOException e){
e.printStackTrace();
}
try{
if(fr != null)
fr.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
2.3.3 FileInputStream 和 FileOutputStream
结论:
- 对于文本文件(.txt , .java, .c, .cpp),使用字符流处理
- 对于非文本文件(.jpg, .mp3, .mp4, .avi, .doc, .ppt,....),使用字节流处理
注:
- 使用FileInputStream处理文本文件可能出现乱码[超过了8位数能表示的范围,如汉字,使用3个字符存储]
- 使用字节流处理文本文件时,只需要实现简单的文本文件的复制操作是可以的,但如果要在内存中读取文本文件则会出错(由于读取的内容可能使字符中断)
//指定路径下非文本文件的复制
@Test
public void testFileInputOutputStream(String srcfile, String destfile){
FileInputStream fis = null;
FileOutputStream fos = null;
try{
//1.读入图片文件
File srcfile = new File(srcfile);
File destfile = new File(destfile);
//2.将文件读入流中
FileInputStream fis = new FileInputStream(srcfile);
FileOutputStream fos = new FileOutputStream(desfile);
//3.数据读入、写出内存
//在内存层面只要不查看中间的内容,就不会出现错误,用字节流实现简单的复制操作是可以的
byte[] buffer = new byte[1024];
while((len = fis.read(buffer)) != -1){
fos.write(arr,0,len);
}
}catch(IOException e){
}finally{
//4.关闭流资源
try{
if(fos != null)
fos.close();
}catch(IOException e){
e.printStackTrace();
}
try{
if(fis != null)
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
@Test
public void testCopyFile(){
long start = System.currentTimeMillis();
String srcPath = "C:\\Users\\Administrator\\Desktop\\01-视频.avi";
String destPath = "C:\\Users\\Administrator\\Desktop\\02-视频.avi";
copyFile(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作所花费的时间为:" + (end - start));//618毫秒
}
2.3.4 处理流之一:缓冲流
BufferedInputStream:
BufferedOutputStream:
BufferedReader:
BufferedWriter:
- 缓冲流的作用:提高流的读取、写入的速度
- 提高读写速度的原因:内部提供了一个缓冲区
- 处理流,就是"套接"在已有的流的基础上
使用BufferedInputStream和BufferedOutputStream实现非文本文件的复制
//实现非文本文件的复制
@Test
public void BufferedStreamTest() throws FileNotFoundException{
//1.造文件
File srcFile = new File("happy.jpg");
File destFile = new File("happy1.jpg");
//2.造流
//2.1 造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileInputStream fos = new FileInputStream(destFile);
//2.2 造处理流(缓冲流)
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[10];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0.len);
}
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
bos.close();
bis.close();
//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,可以省略
fos.close();
fis.close();
}
//改成try-catch结构的说明:
//外面只有缓冲流的对象,不再有节点流的对象
//外面只有这两个
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
@Test
public void testCopyFileWithBuffered(){
long start = System.currentTimeMillis();
String srcPath = "C:\\Users\\Administrator\\Desktop\\01-视频.avi";
String destPath = "C:\\Users\\Administrator\\Desktop\\02-视频.avi";
copyFileWithBuffered(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作所花费的时间为:" + (end - start));//618毫秒 -- 176毫秒
}
使用BufferedReader和BufferedWriter实现文本文件的复制
@Test
public void testBufferedReaderBufferedWriter(){
//创建文件和相应的流
BufferedReader br = new BufferedReader(new FileReader(new File("dbcp.txt")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
//读写操作
//方式一:使用char[]数组
char[] cbuf = new char[1024];
int len;
while((len = br.read(cbuf)) != -1){
bw.write(cbuf,0,len);
}
//方式二:使用String
String data;
while((data = br.readLine()) != null){
//方法1:
bw.write(data + "\n");//data中不包含换行符
//方法2:
bw.write(data);//data中不包含换行符
bw.newLine();//提供换行的操作
}
//关闭资源
bw.close();
br.close();
}
缓冲流练习
练习1:实现图片加密操作
int b = 0; while((b = fis.read()) != -1){ fos.write(b^5);//用异或操作实现图片加密 }
@Test
public void test1(){
FileInputStream fis = new FileInputStream("happy.jpg");
FileOutputStream fos = new FileOutputStream("happy1.jpg");
byte[] cbuf = new byte[20];
int len;
while((len = fis.read(cbuf))!= -1){
for(int i = 0;i < len;i++){
cbuf[i] = cbuf[i] ^ 5;
}
fos.write(cbuf,0,len);
}
fos.close();
fis.close();
}
练习2:获取文本上每个字符出现的次数:
提示:遍历文本的每一个字符:字符及出现的次数保存在Map中:将Map中数据写入文件
@Test
public void test1(){
FileReader fr = new FileReader(srcFile);
Map<char,int> map = new HashMap<>();
char[] cbuf = new char[20];
int len;
while((len = fr.read(cbuf)) != -1){
for(int i = 0;i < len;i++){
if(map.contains(cbuf[i])){
map.replace(cbuf[i],map.get(cbuf[i])++);
}else{
map.put(cbuf[i],1);
}
}
}
fr.close();
}
3 转换流[不熟悉]
转换流:
- InputStreamReader:将一个字节的输入流转换为字符的输入流
- OutputStreamWriter:将一个字符的输出流转换为字节的输出流
作用:提供字节流与字符流之间的转换
编码:字节、字节数组 ---> 字符数组、字符串
解码:字符数组、字符串 ---> 字节、字节数组
ASCII:美国标准信息交换码, 用一个字节的7位可以表示。
ISO8859-1:拉丁码表。欧洲码表, 用一个字节的8位表示。
GB2312:中国的中文编码表。最多两个字节编码所有字符
GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的 字符码。所有的文字都用两个字节来表示。
UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
@Test
public void test(){
FileInputStream fis = new FileInputStream(new File("hello.txt"));
FileOutputStream fos = new FileOutputStream(new File("hello1.txt"));
InputStreamReader isr = new InputStreamReader(fis);//将字节流转为字符流
OutputStreamWriter osw = new OutputStreamWriter(fos);//将字符流转为字节流
int len;
char[] arr = new char[20];
while((len = isr.read(arr)) != -1){
}
}
InputStreamReader:
实现字节的输入流到字符的输入流的转换
//为了保证流的关闭,处理异常要用try-catch-finally
//InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
@Test
public void test1() throws IOException{
//1.造流,造文件
FileInputStream fis = new FileInputStream("dbcp.txt");
//2.将输入字节流转成字符流
//InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集,编译器设定的
//2.将输入的字节流转成字符流,并指明编码集
//参数2指明了字符集,具体使用那个字符集,取决于文件dbcp.txt保存时使用的字符集
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
//3.将文件中的数据取出,放于内存中处理
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
String str = new String(cbuf,0,len);
System.out.println(str);
}
//4.关闭流
isr.close();
}
OutputStreamWriter
//综合使用InputStreamReader 和 OutputStreamWriter
//实现图示代码
@Test
public void InOutputStream(){
FileInputStream fis = new FileInputStream("dbcp.txt");
FileOutputStream fw = new FileOutputStream("dbcp1.txt");
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(fw,"gbk");
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
osw.close();
isr.close();
fw.close();
fis.close();
}
4.其他流的使用
标准的输入、输出流 打印流 和 数据流 --- 了解
4.1 标准的输入、输出流
System.in 和 System.out 分别代表了系统标准的输入和输出设备
默认的输入设备是:键盘,输出设备是:显示器
System.in的类型是InputStream
System.out的类型是PrintStream ,其是OutputStream的子类 FilterOutputStream的子类
重定向:通过System类的setIn,setOut方法对默认设备进行改变
public static void setIn(InputStream in)
public static void setOut(PrintStream out)
- System.in 标准的输入流,默认从键盘输入
System.out: 标准的输出流,默认从控制台(显示器)输出
- System类的setIn(InputStream) / setOut(PrintStream ps)方式重新指定输入和输出的流
练习1:
从键盘输入字符串,要求将读取到的整行字符串转成大写输出,然后继续进行输入操作,直至输入‘e’ 或“exit”时,退出程序
- 使用Scanner 来实现,调用next()返回一个字符串
- 使用System.in实现;System.in --> 转换流-->BufferedReader里的readLine()
@Test
public void test(){
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
while(true){
System.out.println("请输入字符串:");
String data = br.readLine();
if("e".equalsIgnoreCase(data) ||"exit".equalsIgnoreCase(data)){
System.out.println("程序结束");
break;
}
String upperCase = data.toUpperCase();
System.out.println(upperCase);
}
br.close();
}
练习2:
public class MyIput{
public static String readString(){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = "";
try{
string = br.readLine();
}catch(IOException e){
System.out.println(ex);
}
return string;
}
//读取一个整型
public static int readInt(){
return Integer.parseInt(readString());
}
//读取一个双精度型
public static double readDouble(){
return Double.parseDouble(readString());
}
//读取一个字节型
public static byte readByte(){
return Byte.parseByte(readString());
}
//读取一个单精度型
public static short readShort(){
return Short.parseShort(readString());
}
//读取一个long型
public static long readInt(){
return Long.parseLong(readString());
}
}
4.2 打印流
- 实现将基本数据类型的数据格式转化为字符串输出
- 打印流PrintStream和PrintWriter
提供了一系列重载的print()和println()方法,用于多种数据类型的输出
PrintStream和PrintWriter的输出不会抛出IOException异常
PrintStream和PrintWriter有自动flush功能
PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。 在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
System.out返回的是PrintStream的实例
打印流实例(了解):
@Test
public void test(){
PrintStream ps = null;
try{
FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
//创建打印输出流,设置为自动刷新模式(写入换行符或字节'\n'时都会刷新输出缓冲区)
ps = new PrintStream(fos,true);
if(ps != null){//把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for(int i = 0;i <= 255;i++){
System.out.print((char)i);
if(i % 50 == 0){
System.out.println();//换行输出
}
}
}catch(FileNotFoundException e){
e.printStackTrace();
}finally{
if(ps != null)ps.close();
}
}
4.3 数据流
- DataInputStream 和 DataOutputStream
- 作用:用于读取或写出基本数据类型的变量或字符串
练习:将内存中的字符串、基本数据类型的变量写出到文件中
注意:处理异常的话,仍然应该使用try-catch-finally
public void test3() throws IOException{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("d:\\io\\file.txt"));
dos.writeUTF("刘建辰");
dos.flush();//刷新操作,将内存中的数据写入文件
dos.writeInt(23);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.close();
}
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
@Test
public void test4(){
//1.
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
//2.
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name = " + name + ";age = " + age + ";isMale = " + isMale);
//3.关闭流
dis.close();
}
4.4 对象流
ObjectInputStream 和 ObjectOutputStream
- 用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来
- 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
- 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
- ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
对象的序列化
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
要想一个java对象是可序列化的,需要满足相应的要求,如下所示:
Person需要满足如下的要求,方可序列化
1. 需要实现接口:Serializable
2. 当前类提供一个全局常量:serialVersionUID
public static final long serialVersionUID = 4655555567l;
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现
*/
public void testObjectOutputStream(){
ObjectOutputStream oos = null;
try{
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱北京天安门!"));
oos.flush();//刷新操作
}catch (IOException e){
e.printStackTrace();
}finally{
if(oos != null){
try{
oos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
//反序列化:将磁盘文件中的对象还原为内存中的一个java对象
//使用ObjectInputStream来实现
public void testObjectInputStream(){
ObjectInputStream ois = null;
try{
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String)obj;
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}finally{
if(ois != null){
try{
ois.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
5.每天一考
输入、输出的标准化过程
1. 输入过程
① 创建File类的对象,指明读取的数据的来源(要求此文件一定要存在)
② 创建相应的输入流,将File类的对象作为参数,传入流的构造器中
③ 集体的读入过程:
创建相应的byte[ ] 或 char[ ]
④ 关闭流资源
说明:程序中出现的异常需要使用try-catch-finally处理
2. 输出过程
① 创建File类的对象,指明写出的数据的位置(不要求此文件一定要存在)
② 创建相应的输出流,将File类的对象作为参数,传入流的构造器中
③ 具体的写出过程:
write(char[ ]/byte[ ] buffer,0,len)
④ 关闭流资源
说明:程序中出现的异常需要使用try-catch-finally处理
- 说明流的三种分类方式:
数据流向:输入流、输出流
数据单位:字节流、字符流
流的角色:节点流、处理流
- 写出4个IO流中的抽象基类,4个文件流,4个缓冲流
抽象基类:InputStream、OutputStream、Reader、Writer
文件流:FileInputStream、FileOutputStream、FileReader、FileWriter
缓冲流:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter
InputStreamReader:父类 Reader
异常:XxxException XxxError
- 字节流和字符流的区别与使用情境
字节流:read(byte[] buffer) / read() 非文本文件(可以实现对文本文件的简单复制)
字符流:read(char[] cbuf) / read() 文本文件
- 使用缓冲流实现a.jpg文件复制为b.jpg文件的操作
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("a.jpg"))); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("b,jpg"))); byte[] buffer = new byte[1024]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); }
此时的异常应该使用try-catch-finally处理
- 转换流是哪两个类,分别的作用是什么?请分别创建两个类的对象
InputStreamReader:将输入的字节流转换为输入的字符流。解码
OutputStreamWriter:将输出的字符流转换为输出的字节流。编码
InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"),"utf-8"); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt"),"gbk"); //解码注意要根据实际文本文件的编码集来 //编码可以是任意的