File类的使用:
如何创建File类的实例
常用构造器:
File(String filePath)
File(String parentPath,String childPath)
File(File parentFile,String childPath)
相对路径:相较于某个路径下,指明的路径。
绝对路径:包含盘符在内的文件或文件目录的路径
说明:
IDEA中:使用JUnit中的单元测试方法测试,相对路径为当前Module下;使用main()测试,相对路径为当前Project下
Ecplise中:不管使用单元测试方法还是main()测试,相对路径都为当前Project下
路径分隔符
windows:
unix:/
@Test
public void test1(){//构造器1File file1 = new File(");//相对于当前moduleFile file2 = new File("D:\workspace_idea1\JavaSenior\day08\he.txt");System.out.println(file1);//System.out.println(file2);//D:workspace_idea1JavaSenior//构造器2:File file3 = new File("D:\workspace_idea1","JavaSenior");System.out.println(file3);//D:workspace_idea1JavaSenior//构造器3:File file4 = new File(file3,");System.out.println(file4);//D:workspace_idea1
}
常用方法:
File类的获取功能
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
public long lastModified() :获取最后一次的修改时间,毫秒值
如下的两个方法适用于文件目录:
File类的重命名功能
public boolean renameTo(File dest):把文件重命名为指定的文件路径
比如ameTo(file2)为例:要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
File类的判断功能
File类的创建功能:创建硬盘中对应的文件或文件目录
@Testpublic void test6() throws IOException {File file1 = new File(");if(!ists()){//文件的创建ateNewFile();System.out.println("创建成功");}else{//文件存在file1.delete();System.out.println("删除成功");}}
File类的删除功能:删除磁盘中的文件或文件目录
课后练习:
package 1;import org.junit.Test;import java.io.File;
import java.io.FilenameFilter;public class FindJPGFileTest {@Testpublic void test1(){File srcFile = new File("d:\code");String[] fileNames = srcFile.list();for(String fileName : fileNames){dsWith(".jpg")){System.out.println(fileName);}}}@Testpublic void test2(){File srcFile = new File("d:\code");File[] listFiles = srcFile.listFiles();for(File file : listFiles){Name().endsWith(".jpg")){System.out.AbsolutePath());}}}/** File类提供了两个文件过滤器方法* public String[] list(FilenameFilter filter)* public File[] listFiles(FileFilter filter)*/@Testpublic void test3(){File srcFile = new File("d:\code");File[] subFiles = srcFile.listFiles(new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {dsWith(".jpg");}});for(File file : subFiles){System.out.AbsolutePath());}}
}
package 1;import java.io.File;public class ListFilesTest {public static void main(String[] args) {// 递归:文件目录/** 打印出指定目录所有文件名称,包括子文件目录中的文件 */// 1.创建目录对象File dir = new File("E:\teach\01_javaSE\_尚硅谷Java编程语言\3_软件");// 2.打印目录的子文件printSubFile(dir);}public static void printSubFile(File dir) {// 打印目录的子文件File[] subfiles = dir.listFiles();for (File f : subfiles) {if (f.isDirectory()) {// 文件目录printSubFile(f);} else {// 文件System.out.AbsolutePath());}}}// 方式二:循环实现// 列出file目录的下级内容,仅列出一级的话// 使用File类的String[] list()比较简单public void listSubFiles(File file) {if (file.isDirectory()) {String[] all = file.list();for (String s : all) {System.out.println(s);}} else {System.out.println(file + "是文件!");}}// 列出file目录的下级,如果它的下级还是目录,接着列出下级的下级,依次类推// 建议使用File类的File[] listFiles()public void listAllSubFiles(File file) {if (file.isFile()) {System.out.println(file);} else {File[] all = file.listFiles();// 如果all[i]是文件,直接打印// 如果all[i]是目录,接着再获取它的下一级for (File f : all) {listAllSubFiles(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);// f的大小;}}return size;}// 拓展2:删除指定的目录public void deleteDirectory(File file) {// 如果file是文件,直接delete// 如果file是目录,先把它的下一级干掉,然后删除自己if (file.isDirectory()) {File[] all = file.listFiles();// 循环删除的是file的下一级for (File f : all) {// f代表file的每一个下级deleteDirectory(f);}}// 删除自己file.delete();}
}
抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer))
OutputStream FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush()
Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine())
Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / newLine() / flush()
FileReader和FileWriter为访问文件的字符输入输出流,不能使用字符流来处理图片等字节数据
FileReader
@Testpublic void testFileReader(){FileReader fr = null;try {//1.实例化File类的对象,指明要操作的文件File file = new File(");//相较于当前Module//2.提供具体的流fr = new FileReader(file);//3.数据的读入//read():返回读入的一个字符。如果达到文件末尾,返回-1//方式一:
// int data = fr.read();
// while(data != -1){
// System.out.print((char)data);
// data = fr.read();
// }//方式二:语法上针对于方式一的修改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();
// }//或if(fr != null){try {fr.close();} catch (IOException e) {e.printStackTrace();}}}}
read(char cbuf[])
,返回值为读入的字符数组的长度 @Testpublic void testFileReader1() {FileReader fr = null;try {//1.File类的实例化File file = new File(");//2.FileReader流的实例化fr = new FileReader(file);//3.读入的操作//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1char[] cbuf = new char[5];int len;while((len = fr.read(cbuf)) != -1){//方式一://错误的写法//最后的字符个数不足char[]的长度时,cbuf.length会输出整个数组,包括上一组未被覆盖的字符
// for(int i = 0;i < cbuf.length;i++){
// System.out.print(cbuf[i]);
// }//正确的写法
// for(int i = 0;i < len;i++){
// System.out.print(cbuf[i]);
// }//方式二://错误的写法,对应着方式一的错误的写法
// String str = new String(cbuf);
// System.out.print(str);//正确的写法String str = new String(cbuf,0,len);System.out.print(str);}} catch (IOException e) {e.printStackTrace();} finally {if(fr != null){//4.资源的关闭try {fr.close();} catch (IOException e) {e.printStackTrace();}}}}
FileWriter
@Testpublic void testFileWriter() {FileWriter fw = null;try {//1.提供File类的对象,指明写出到的文件File file = new File(");//2.提供FileWriter的对象,用于数据的写出fw = new FileWriter(file,false);//3.写出的操作fw.write("I have a dream!n");fw.write("you need to have a dream!");} catch (IOException e) {e.printStackTrace();} finally {//4.流资源的关闭if(fw != null){try {fw.close();} catch (IOException e) {e.printStackTrace();}}}}
例题:将的内容复制到中
@Testpublic void testFileReaderFileWriter() {FileReader fr = null;FileWriter fw = null;try {//1.创建File类的对象,指明读入和写出的文件File srcFile = new File(");File destFile = new File(");//不能使用字符流来处理图片等字节数据
// File srcFile = new File("爱情与友情.jpg");
// File destFile = new File("爱情与友情1.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();
// }finally{
// try {
// if(fr != null)
// fr.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }//方式二:try {if(fw != null)fw.close();} catch (IOException e) {e.printStackTrace();}try {if(fr != null)fr.close();} catch (IOException e) {e.printStackTrace();}}}
@Test
public void testFileInputStream() {FileInputStream fis = null;try {//1. 造文件File file = new File(");//2.造流fis = new FileInputStream(file);//3.读数据byte[] buffer = new byte[5];int len;//记录每次读取的字节的个数while((len = ad(buffer)) != -1){String str = new String(buffer,0,len);System.out.print(str);}} catch (IOException e) {e.printStackTrace();} finally {if(fis != null){//4.关闭资源try {fis.close();} catch (IOException e) {e.printStackTrace();}}}
}
输出结果:@Test
public void testFileInputOutputStream() {FileInputStream fis = null;FileOutputStream fos = null;try {//File srcFile = new File("爱情与友情.jpg");File destFile = new File("爱情与友情2.jpg");//fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);//复制的过程byte[] buffer = new byte[5];int len;while((len = ad(buffer)) != -1){fos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {if(fos != null){//try {fos.close();} catch (IOException e) {e.printStackTrace();}}if(fis != null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}}
}
将复制操作改写为函数,实现指定路径下文件的复制://指定路径下文件的复制
public void copyFile(String srcPath,String destPath){FileInputStream fis = null;FileOutputStream fos = null;try {//File srcFile = new File(srcPath);File destFile = new File(destPath);//fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);//复制的过程byte[] buffer = new byte[1024];int len;while((len = ad(buffer)) != -1){fos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {if(fos != null){//try {fos.close();} catch (IOException e) {e.printStackTrace();}}if(fis != null){try {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";// String srcPath = ";
// String destPath = ";copyFile(srcPath,destPath);long end = System.currentTimeMillis();System.out.println("复制操作花费的时间为:" + (end - start));//618
}
package com.atguigu.java;import org.junit.Test;import java.io.*;public class BufferedTest {/*实现非文本文件的复制*/@Testpublic void BufferedStreamTest() throws FileNotFoundException {BufferedInputStream bis = null;BufferedOutputStream bos = null;try {//1.造文件File srcFile = new File("爱情与友情.jpg");File destFile = new File("爱情与友情3.jpg");//2.造流//2.1 造节点流FileInputStream fis = new FileInputStream(srcFile);FileOutputStream fos = new FileOutputStream(destFile);//2.2 造缓冲流bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);//3.复制的细节:读取、写入byte[] buffer = new byte[10];int len;while((len = ad(buffer)) != -1){bos.write(buffer,0,len);// bos.flush();//刷新缓冲区}} catch (IOException e) {e.printStackTrace();} finally {//4.资源关闭//要求:先关闭外层的流,再关闭内层的流if(bos != null){try {bos.close();} catch (IOException e) {e.printStackTrace();}}if(bis != null){try {bis.close();} catch (IOException e) {e.printStackTrace();}}//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
// fos.close();
// fis.close();}}//实现文件复制的方法public void copyFileWithBuffered(String srcPath,String destPath){BufferedInputStream bis = null;BufferedOutputStream bos = null;try {//1.造文件File srcFile = new File(srcPath);File destFile = new File(destPath);//2.造流//2.1 造节点流FileInputStream fis = new FileInputStream((srcFile));FileOutputStream fos = new FileOutputStream(destFile);//2.2 造缓冲流bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);//3.复制的细节:读取、写入byte[] buffer = new byte[1024];int len;while((len = ad(buffer)) != -1){bos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4.资源关闭//要求:先关闭外层的流,再关闭内层的流if(bos != null){try {bos.close();} catch (IOException e) {e.printStackTrace();}}if(bis != null){try {bis.close();} catch (IOException e) {e.printStackTrace();}}//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
// fos.close();
// fis.close();}}@Testpublic void testCopyFileWithBuffered(){long start = System.currentTimeMillis();String srcPath = "C:\Users\Administrator\Desktop\01-视频.avi";String destPath = "C:\Users\Administrator\Desktop\03-视频.avi";copyFileWithBuffered(srcPath,destPath);long end = System.currentTimeMillis();System.out.println("复制操作花费的时间为:" + (end - start));//618 -> 176}/*使用BufferedReader和BufferedWriter实现文本文件的复制*/@Testpublic void testBufferedReaderBufferedWriter(){BufferedReader br = null;BufferedWriter bw = null;try {//创建文件和相应的流br = new BufferedReader(new FileReader(new File(")));bw = new BufferedWriter(new FileWriter(new File(")));//读写操作//方式一:使用char[]数组
// char[] cbuf = new char[1024];
// int len;
// while((len = br.read(cbuf)) != -1){
// bw.write(cbuf,0,len);
// // bw.flush();
// }//方式二:使用StringString data;while((data = br.readLine()) != null){//方法一:
// bw.write(data + "n");//data中不包含换行符//方法二:bw.write(data);//data中不包含换行符bw.newLine();//提供换行的操作}} catch (IOException e) {e.printStackTrace();} finally {//关闭资源if(bw != null){try {bw.close();} catch (IOException e) {e.printStackTrace();}}if(br != null){try {br.close();} catch (IOException e) {e.printStackTrace();}}}}
}
package ;import org.junit.Test;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class PicTest {//图片的加密@Testpublic void test1() {FileInputStream fis = null;FileOutputStream fos = null;try {fis = new FileInputStream("爱情与友情.jpg");fos = new FileOutputStream("爱情与友情secret.jpg");byte[] buffer = new byte[20];int len;while ((len = ad(buffer)) != -1) {//字节数组进行修改//错误的// for(byte b : buffer){// b = (byte) (b ^ 5);// }//正确的for (int i = 0; i < len; i++) {buffer[i] = (byte) (buffer[i] ^ 5);}fos.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}//图片的解密@Testpublic void test2() {FileInputStream fis = null;FileOutputStream fos = null;try {fis = new FileInputStream("爱情与友情secret.jpg");fos = new FileOutputStream("爱情与友情4.jpg");byte[] buffer = new byte[20];int len;while ((len = ad(buffer)) != -1) {//字节数组进行修改//错误的// for(byte b : buffer){// b = (byte) (b ^ 5);// }//正确的for (int i = 0; i < len; i++) {buffer[i] = (byte) (buffer[i] ^ 5);}fos.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
}
package ;import org.junit.Test;import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;/*** 获取文本上每个字符出现的次数* 提示:遍历文本的每一个字符;字符及出现的次数保存在Map中;* 将Map中数据写入文件** @author WenYi* @create 2022-06-15 17:05*/
public class WordCount {/*说明:如果使用单元测试,文件相对路径为当前module如果使用main()测试,文件相对路径为当前工程*/@Testpublic void testWordCount(){FileReader fr = null;BufferedWriter bw = null;try {//1. 创建Map集合Map<Character, Integer> map = new HashMap<>();//2. 遍历每一个字符,每一个字符出现的次数放到map中fr = new FileReader(");int c = 0;while((c = fr.read()) != -1){char ch = (char) c;//判断char是否在map中第一次出现ainsKey(ch) == false){map.put(ch, 1);}else{map.put(ch, (ch) + 1);}}//3. 把map中数据存在文件//3.1 创建Writerbw = new BufferedWriter(new FileWriter("));//3.2 遍历map,再写入数据Set<Map.Entry<Character, Integer>> entries = Set();for(Map.Entry<Character, Integer> entry : entries){switch (Key()){case ' ':bw.write("空格=" + Value());break;case 't'://t表示tab 键字符bw.write("tab键=" + Value());break;case 'r'://bw.write("回车=" + Value());break;case 'n'://bw.write("换行=" + Value());break;default:bw.Key() + "=" + Value());break;}bw.newLine();//换行}} catch (IOException e) {throw new RuntimeException(e);} finally {//4. 流的关闭操作if(bw != null){try {bw.close();} catch (IOException e) {throw new RuntimeException(e);}}if(fr != null){try {fr.close();} catch (IOException e) {throw new RuntimeException(e);}}}}
}
转换流:属于字符流,操作的都是char[]。
传入的参数均为字节流,只是底层操作不同。
InputStreamReader:将一个字节的输入流转换为字符的输入流
OutputStreamWriter:将一个字符的输出流转换为字节的输出流
作用:提供字节流与字符流之间的转换
解码:字节、字节数组 —> 字符数组、字符串 —> InputStreamReader
编码:字符数组、字符串 —> 字节、字节数组 —> OutputStreamWriter
代码实现:
@Test
public void test1(){InputStreamReader isr = null;try {FileInputStream fis = new FileInputStream(");//使用系统默认的字符集
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集//参数2指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集isr = new InputStreamReader(fis,"UTF-8");char[] cbuf = new char[20];int len;while((len = ad(cbuf)) != -1){String str = new String(cbuf,0,len);System.out.print(str);}} catch (IOException e) {throw new RuntimeException(e);} finally {if(isr != null){try {isr.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}
@Test
public void test2(){InputStreamReader isr = null;OutputStreamWriter osw = null;try {//1.造文件、造流File file1 = new File(");File file2 = new File("");FileInputStream fis = new FileInputStream(file1);FileOutputStream fos = new FileOutputStream(file2);isr = new InputStreamReader(fis,"utf-8");osw = new OutputStreamWriter(fos,"gbk");//2.读写过程char[] cbuf = new char[20];int len;while((len = ad(cbuf)) != -1){osw.write(cbuf,0,len);}} catch (IOException e) {throw new RuntimeException(e);} finally {//3.关闭资源if(isr != null){try {isr.close();} catch (IOException e) {throw new RuntimeException(e);}}if(osw != null){try {osw.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}
字符集说明:
标准的输入、输出流
System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流。
练习:
//idea不支持在单元测试方法中使用键盘获得System.in的输入,因此要在main方法中实现
public static void main(String[] args) {BufferedReader br = null;try {//将输入的字节流转换为字符流InputStreamReader isr = new InputStreamReader(System.in);//将字符流转换为缓冲流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 = UpperCase();System.out.println(upperCase);}} catch (IOException e) {e.printStackTrace();} finally {if (br != null) {try {br.close();} catch (IOException e) {e.printStackTrace();}}}
}
package ;
// MyInput.java: Contain the methods for reading int, double, float, boolean, short, byte and
// string values from the keyboardimport java.io.*;public class MyInput {// Read a string from the keyboardpublic static String readString() {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));// Declare and initialize the stringString string = "";// Get the string from the keyboardtry {string = br.readLine();} catch (IOException ex) {System.out.println(ex);}// Return the string obtained from the keyboardreturn string;}// Read an int value from the keyboardpublic static int readInt() {return Integer.parseInt(readString());}// Read a double value from the keyboardpublic static double readDouble() {return Double.parseDouble(readString());}// Read a byte value from the keyboardpublic static double readByte() {return Byte.parseByte(readString());}// Read a short value from the keyboardpublic static double readShort() {return Short.parseShort(readString());}// Read a long value from the keyboardpublic static double readLong() {return Long.parseLong(readString());}// Read a float value from the keyboardpublic static double readFloat() {return Float.parseFloat(readString());}
}
@Test
public void test2() {PrintStream ps = null;try {FileOutputStream fos = new FileOutputStream(new File("D:\IO\"));// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 'n' 时都会刷新输出缓冲区)ps = new PrintStream(fos, true);if (ps != null) {// 把标准输出流(控制台输出)改成文件System.setOut(ps);}for (int i = 0; i <= 255; i++) { // 输出ASCII字符System.out.print((char) i);if (i % 50 == 0) { // 每50个数据一行System.out.println(); // 换行}}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (ps != null) {ps.close();}}
}
@Test
public void test3(){DataOutputStream dos = null;try {//1.创建流dos = new DataOutputStream(new FileOutputStream("));//2.操作dos.writeUTF("刘建辰");dos.flush();//刷新操作,将内存中的数据写入文件dos.writeInt(23);dos.flush();dos.writeBoolean(true);dos.flush();} catch (IOException e) {throw new RuntimeException(e);} finally {//3.流的关闭if(dos != null){try {dos.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}
@Test
public void test4(){DataInputStream dis = null;try {//1.创建流dis = new DataInputStream(new FileInputStream("));//2.操作String name = adUTF();int age = adInt();boolean isMale = adBoolean();System.out.println("name = " + name);System.out.println("age = " + age);System.out.println("isMale = " + isMale);} catch (IOException e) {throw new RuntimeException(e);} finally {//3.流的关闭if(dis != null){try {dis.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}
ObjectInputStream和OjbectOutputSteam
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现*/
@Test
public void testObjectOutputStream(){ObjectOutputStream oos = null;try {//1.造流oos = new ObjectOutputStream(new FileOutputStream("object.dat"));//2.操作oos.writeObject(new String("我爱北京天安门"));oos.flush();//刷新操作oos.writeObject(new Person("王铭",23));oos.flush();oos.writeObject(new Person("张学良",23,1001,new Account(5000)));oos.flush();} catch (IOException e) {e.printStackTrace();} finally {if(oos != null){//3.关流try {oos.close();} catch (IOException e) {e.printStackTrace();}}}}
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
/*
反序列化:将磁盘文件中的对象还原为内存中的一个java对象
使用ObjectInputStream来实现*/
@Test
public void testObjectInputStream(){ObjectInputStream ois = null;try {ois = new ObjectInputStream(new FileInputStream("object.dat"));Object obj = adObject();String str = (String) obj;Person p = (Person) adObject();Person p1 = (Person) adObject();System.out.println(str);System.out.println(p);System.out.println(p1);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if(ois != null){try {ois.close();} catch (IOException e) {e.printStackTrace();}}}
}
对象序列化机制:
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点(序列化)。
当其它程序获取了这种二进制流,就可以恢复成原来的Java对象(反序列化)。
要想一个java对象是可序列化的,需要满足相应的要求:
package com.atguigu.java;import java.io.Serializable;public class Person implements Serializable{public static final long serialVersionUID = 475463534532L;private String name;private int age;private int id;private Account acct;public Person(String name, int age, int id) {this.name = name;this.age = age;this.id = id;}public Person(String name, int age, int id, Account acct) {this.name = name;this.age = age;this.id = id;this.acct = acct;}@Overridepublic String toString() {return "Person{" +"name='" + name + ''' +", age=" + age +", id=" + id +", acct=" + acct +'}';}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Person(String name, int age) {this.name = name;this.age = age;}public Person() {}
}class Account implements Serializable{public static final long serialVersionUID = 4754534532L;private double balance;@Overridepublic String toString() {return "Account{" +"balance=" + balance +'}';}public double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}public Account(double balance) {this.balance = balance;}
}
RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。
并且它实现了DataInput、DataOutput这两个接口,既可以作为一个输入流,又可以作为一个输出流,也就意味着这个类既可以读也可以写。
RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读、写文件
RandomAccessFile 类
@Test
public void test1() {RandomAccessFile raf1 = null;RandomAccessFile raf2 = null;try {//1.造流raf1 = new RandomAccessFile(new File("爱情与友情.jpg"),"r");raf2 = new RandomAccessFile(new File("爱情与友情1.jpg"),"rw");//2.复制操作byte[] buffer = new byte[1024];int len;while((len = ad(buffer)) != -1){raf2.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//3.关流if(raf1 != null){try {raf1.close();} catch (IOException e) {e.printStackTrace();}}if(raf2 != null){try {raf2.close();} catch (IOException e) {e.printStackTrace();}}}
}
RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。RandomAccessFile 类对象可以自由移动记录指针:
@Test
public void test2() throws IOException {RandomAccessFile raf1 = new RandomAccessFile(","rw");raf1.seek(3);//将指针调到角标为3的位置,会从3开始覆盖原文件,如abcdefgh->abcxyzghraf1.write("xyz".getBytes());//raf1.close();}
可以通过相关的操作,实现RandomAccessFile“插入”数据的效果
@Test
public void test3() throws IOException {RandomAccessFile raf1 = new RandomAccessFile(","rw");raf1.seek(3);//将指针调到角标为3的位置//保存指针3后面的所有数据到StringBuilder中StringBuilder builder = new StringBuilder((int) new File(").length());byte[] buffer = new byte[20];int len;while((len = ad(buffer)) != -1){builder.append(new String(buffer,0,len)) ;}//调回指针,写入“xyz”raf1.seek(3);raf1.write("xyz".getBytes());//将StringBuilder中的数据写入到文件中raf1.String().getBytes());raf1.close();//思考:将StringBuilder替换为ByteArrayOutputStream
}
可以用RandomAccessFile这个类,来实现一个多线程断点下载的功能,用过下载工具的朋友们都知道,下载前都会建立两个临时文件,一个是与被下载文件大小相同的空文件,另一个是记录文件指针的位置文件,每次暂停的时候,都会保存上一次的指针,然后断点下载的时候,会继续从上一次的地方下载,从而实现断点下载或上传的功能。
Java NIO 概述
NIO. 2
随着 JDK 7 的发布,Java对NIO进行了极大的扩展,增强了对文件处理和文件系统特性的支持,称为 NIO.2。因为 NIO 提供的一些功能,NIO已经成为文件处理中越来越重要的部分。
Path、Paths和Files核心API
Path接口
Files工具类
Paths工具类
Paths 类提供的静态 get() 方法用来获取 Path 对象:
static Path get(String first, String … more) : 用于将多个字符串串连成路径
static Path get(URI uri): 返回指定uri对应的Path路径
实际开发中,经常使用第三方jar包中的工具类进行数据的读写,如FileUtils
package com.atguigu.java;import org.apachemons.io.FileUtils;import java.io.File;
import java.io.IOException;public class FileUtilsTest {public static void main(String[] args) {File srcFile = new File("day10\爱情与友情.jpg");File destFile = new File("day10\爱情与友情2.jpg");try {pyFile(srcFile,destFile);} catch (IOException e) {e.printStackTrace();}}
}
本文发布于:2024-01-31 23:12:34,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170671395432081.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |