一、File類(lèi)的使用
1.File類(lèi)的一個(gè)對(duì)象,代表一個(gè)文件或一個(gè)文件目錄(俗稱:文件夾)
2.File了聲明在java.io包下
3.File類(lèi)中涉及到關(guān)于文件或文件目錄的創(chuàng)建、刪除、重命名、修改時(shí)間、文件大小等方法。
并涉及到寫(xiě)入或讀取文件內(nèi)容的操作。入宮需要讀取或?qū)懭胛募?nèi)容,必須使用IO流來(lái)完成。
4.后續(xù)File類(lèi)的對(duì)象常會(huì)作為參數(shù)傳遞到流的構(gòu)造器中,指明讀取或?qū)懭氲?quot;終點(diǎn)"。
A.常用構(gòu)造器
B.路徑分隔符
/* 1.如何創(chuàng)建File類(lèi)的實(shí)例 File(String filePath) File(String parentPath,String,childPath) File(File parentFile,String childPath) 2.相對(duì)路徑:相較于某個(gè)路徑下,知名的路徑。 絕對(duì)路徑:包含盤(pán)符在內(nèi)的未見(jiàn)或文件目錄的路徑 3.路徑分隔符 windows: unix:/ */ public void test1() { //構(gòu)造器1 File file1 = new File("hello.txt");//相對(duì)于module File file2 = new File("E:zxdymIDEAcodeJavaSenior2021_08he.txt"); System.out.println(file1); System.out.println(file2); //構(gòu)造器2 File file3 = new File("E:zxdymIDEAcode", "JavaSenior"); System.out.println(file3); //構(gòu)造器3 File file4 = new File(file3, "hi.txt"); System.out.println(file4); }
C.常用方法
public void test2() { File file1 = new File("hello.txt"); File file2 = new File("d:iohi.txt"); System.out.println(file1.getAbsolutePath()); System.out.println(file1.getPath()); System.out.println(file1.getName()); System.out.println(file1.getParent()); System.out.println(file1.length()); System.out.println(new Date(file1.lastModified())); System.out.println(); System.out.println(file2.getAbsolutePath()); System.out.println(file2.getPath()); System.out.println(file2.getName()); System.out.println(file2.getParent()); System.out.println(file2.length()); System.out.println(file2.lastModified()); } public void test3() { File file = new File("E:\zxdym\IDEA\code\JavaSenior"); String[] list = file.list(); for (String s : list) { System.out.println(s); } System.out.println(); File[] files = file.listFiles(); for (File f : files) { System.out.println(f); } } /* public boolean removeTo(File dest):把文件重命名為指定的文件路徑 比如:file1.renameTo(file2)為例: 要想保證返回true,需要file1在硬盤(pán)中是存在的,且file2不能在硬盤(pán)中存在。 */ @Test public void test4() { File file1 = new File("hello.txt"); File file2 = new File("D:iohi.txt"); boolean renameTo = file1.renameTo(file2); System.out.println(renameTo); } @Test public void test5() { File file1 = new File("hello.txt"); System.out.println(file1.isDirectory()); System.out.println(file1.isFile()); System.out.println(file1.exists()); System.out.println(file1.canRead()); System.out.println(file1.canWrite()); System.out.println(file1.isHidden()); } @Test public void test6() throws IOException { File file1 = new File("hi.txt"); if (!file1.exists()) { file1.createNewFile(); System.out.println("創(chuàng)建成功"); } else {//文件存在 file1.delete(); System.out.println("刪除成功"); } } @Test public void test7(){ //文件目錄的創(chuàng)建 File file1 = new File("e:ioio1io3"); boolean mkdir = file1.mkdir(); if(mkdir){ System.out.println("創(chuàng)建成功1"); } File file2 = new File("e:ioio1io3"); boolean mkdir1 = file1.mkdirs(); if(mkdir1){ System.out.println("創(chuàng)建成功2"); } }
D.注意點(diǎn)
二、流的分類(lèi)及其體系
開(kāi)發(fā)中,用緩沖流,效率比節(jié)點(diǎn)流高(藍(lán)色框中的表示重要的、常用的)
輸入、輸出的標(biāo)準(zhǔn)化過(guò)程
1.輸入過(guò)程
A.創(chuàng)建File類(lèi)的對(duì)象,指明讀取的數(shù)據(jù)的來(lái)源。(要求此文件一定要存在)
B.創(chuàng)建相應(yīng)的輸入流,將File類(lèi)的對(duì)象作為參數(shù),傳入流的構(gòu)造器中
C.具體的讀入過(guò)程:
創(chuàng)建相應(yīng)的byte[] 或 char[]
D.關(guān)閉流資源
說(shuō)明:程序中出現(xiàn)的異常需要使用try-catch-finally處理。
2.輸出過(guò)程
A.創(chuàng)建File類(lèi)的對(duì)象,指明寫(xiě)出的數(shù)據(jù)的來(lái)源。(要求此文件一定要存在)
B.創(chuàng)建相應(yīng)的輸出流,將File類(lèi)的對(duì)象作為參數(shù),傳入流的構(gòu)造器中
C.具體的寫(xiě)出過(guò)程:
write(char[]/byte[] buffer,0,len)
D.關(guān)閉流資源
說(shuō)明:程序中出現(xiàn)的異常需要使用try-catch-finally處理。
public class FileReaderWriterTest { public static void main(String[] args) { File file = new File("hello.txt");//相較于前工程 System.out.println(file.getAbsolutePath()); File file1 = new File("2021_08hello.txt"); System.out.println(file1.getAbsolutePath()); } /* 將day09下的hello.txt文件內(nèi)容讀入程序中,并輸出到控制臺(tái) 說(shuō)明點(diǎn): 1.read()的理解,返回讀入的一個(gè)字符,如果達(dá)到文件末尾,返回-1 2.異常的處理:為了保證流資源一定可以執(zhí)行關(guān)閉操作。需要使用try-catch-finally處理 3.讀入的文件一定要存在,否則就會(huì)報(bào)FileNotFoundException. */ @Test public void testFileReader(){ FileReader fr = null; try { //1.實(shí)例化File類(lèi)的對(duì)象,指明要操作的文件 File file = new File("hello.txt");//相較于當(dāng)前Module //2.提供具體的流 fr = new FileReader(file); //3.數(shù)據(jù)的讀入 //read():返回讀入的一個(gè)字符,如果達(dá)到文件末尾,返回-1 //方式一: // int data = fr.read(); // while(data != -1){ // System.out.print((char)data); // data = fr.read(); // } //方式二:語(yǔ)法上針對(duì)方式一的修改 int data; while((data = fr.read()) != -1){ System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); } finally { //4.流的關(guān)閉操作 try { if(fr != null) fr.close(); } catch (IOException e) { e.printStackTrace(); } finally { } } } @Test public void testFileReader1(){ FileReader fr = null; try { //1.File類(lèi)的實(shí)例化 File file = new File("hello.txt"); //2.FileReader流的實(shí)例化 fr = new FileReader(file); //3.讀入的操作 //read(char[] cbuf):返回每次讀入cbuf數(shù)組中的字符的個(gè)數(shù),如果達(dá)到文件末尾,返回-1 char[] cbuf = new char[5]; int len; while(( len = fr.read(cbuf)) != -1){ //方式一: //錯(cuò)誤的寫(xiě)法//知識(shí)點(diǎn)難點(diǎn):數(shù)組元素的覆蓋 // for(int i = 0;i < cbuf.length;i++){ // System.out.print(cbuf[i]); // } //正確的寫(xiě)法 // for(int i = 0;i < len;i++){ // System.out.print(cbuf[i]); // } //方式二: //錯(cuò)誤的寫(xiě)法,對(duì)應(yīng)著方式一的錯(cuò)誤的寫(xiě)法 // String str = new String(cbuf); // System.out.println(str); //正確的寫(xiě)法 String str = new String(cbuf, 0, len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if(fr != null){ //4.資源的關(guān)閉 try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* 從內(nèi)存中寫(xiě)出數(shù)據(jù)到硬盤(pán)的文件里 說(shuō)明: 1.輸出操作,對(duì)應(yīng)的File可以不存在的,并不會(huì)報(bào)異常 2. File對(duì)應(yīng)的硬盤(pán)中的文件如果不存在,在輸出的過(guò)程中,會(huì)自動(dòng)創(chuàng)建此文件 File對(duì)應(yīng)的硬盤(pán)中的文件如果存在: 如果流使用的構(gòu)造器是:FileWriter(file,false) / FileWriter(file):對(duì)原有文件的覆蓋 如果流使用的構(gòu)造器是:FileWriter(file,true):不會(huì)對(duì)原有文件覆蓋,而是在原有文件基礎(chǔ)上追加內(nèi)容 */ @Test public void testFileWriter() { FileWriter fw = null; try { //1.提供File類(lèi)的對(duì)象,指明寫(xiě)出到的文件 File file = new File("hello1.txt"); //2.提供FileWriter的對(duì)象,用于數(shù)據(jù)的寫(xiě)出 fw = new FileWriter(file,false); //3.寫(xiě)出的操作 fw.write("I have a dream! "); fw.write("you need to have a dream!"); } catch (IOException e) { e.printStackTrace(); } finally { //4.流資源的關(guān)閉 if(fw != null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testFileReaderFileWriter(){ FileReader fr = null; FileWriter fw = null; try { //1.創(chuàng)建File類(lèi)的對(duì)象,指明讀入和寫(xiě)出的文件 File srcFile = new File("hello.txt"); File destFile = new File("hello2.txt"); //不能使用字符流來(lái)處理圖片等字節(jié)數(shù)據(jù) // File srcFile = new File("愛(ài)情與友情.jpg"); File destFile = new File("愛(ài)情與友情1.jpg"); //2.創(chuàng)建數(shù)據(jù)入流和輸出流的對(duì)象 fr = new FileReader(srcFile); fw = new FileWriter(destFile); //3.數(shù)據(jù)的讀入和寫(xiě)出操作 char[] cbuf = new char[5]; int len;//記錄每次讀入到cbuf數(shù)組中的字符的個(gè)數(shù) while((len = fr.read(cbuf)) != -1){ //每次寫(xiě)出len個(gè)字符 fw.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { // //4.關(guān)閉流資源 // //方式一: // try { // fw.close(); // } catch (IOException e) { // e.printStackTrace(); // }finally { // try { // fr.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } //方式二: try { fw.close(); } catch (IOException e) { e.printStackTrace(); } try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
三、流的詳細(xì)介紹
1.字節(jié)流和字符流
測(cè)試FileInputStream和FileOutputStream的使用 public class FileInputOutputStreamTest { //使用字節(jié)流FileInputOutputStream處理文本文件,可能出現(xiàn)亂碼 @Test public void testFileInputStream(){ FileInputStream fis = null; try { //1.造文件 File file = new File("hello.txt"); //2.造流 fis = new FileInputStream(file); //3.讀數(shù)據(jù) byte[] buffer = new byte[5]; int len;//記錄每次讀取的字節(jié)的個(gè)數(shù) while((len = fis.read(buffer)) != -1){ String str = new String(buffer, 0, len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { //4.關(guān)閉資源 try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } /* 實(shí)現(xiàn)對(duì)圖片的復(fù)制操作 */ @Test public void testFileInputOutputStream(){ FileInputStream fis = null; FileOutputStream fos = null; try { File srcFile = new File("愛(ài)情與友情.jpg"); File destFile = new File("愛(ài)情與友情2.jpg"); fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //復(fù)制的過(guò)程 byte[] buffer = new byte[5]; int len; while((len = fis.read(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(); } } } } //指定路徑下文件的復(fù)制 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); //復(fù)制的過(guò)程 byte[] buffer = new byte[5]; int len; while((len = fis.read(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:UsersAdministratorDesktop1-視頻.avi"; String destPath = "C:UsersAdministratorDesktop2-視頻.avi"; copyFile(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("復(fù)制操作花費(fèi)的時(shí)間為:" + (end - start)); } }
結(jié)論:
1.對(duì)于文本文件(.txt,.java,.c,.cpp),使用字符流處理
2.對(duì)于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字節(jié)流處理
2.節(jié)點(diǎn)流和處理流(重點(diǎn))
處理流之一:緩沖流的作用
1.緩沖流:
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
2.作用:提高流的讀取,寫(xiě)入的速度
提高讀寫(xiě)速度的原因:內(nèi)部提供了一個(gè)緩沖區(qū),默認(rèn)情況是8kb
3.處理流:就是"套接"在已有流的基礎(chǔ)上
public class BufferedTest { @Test public void BufferedStreamTest(){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1.造文件 File srcFile = new File("愛(ài)情與友情.jpg"); File destFile = new File("愛(ài)情與友情3.jpg"); //2.造流 //2.1造節(jié)點(diǎn)流 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); //2.2造緩沖流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3.復(fù)制的細(xì)節(jié):讀取、寫(xiě)入 byte[] buffer = new byte[10]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); // bos.flush();//刷新緩沖區(qū) } } catch (IOException e) { e.printStackTrace(); } finally { //4.資源關(guān)閉 //要求:先關(guān)閉外層的流,再關(guān)閉內(nèi)層的流 if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //說(shuō)明:關(guān)閉外層流的同時(shí),內(nèi)層流也會(huì)自動(dòng)的進(jìn)行關(guān)閉,關(guān)于內(nèi)層流的關(guān)閉,可以省略 // fos.close(); // fis.close(); } } @Test public void testCopyFileWithBuffered(){ long start = System.currentTimeMillis(); String srcPath = "C:UsersAdministratorDesktop1-視頻.avi"; String destPath = "C:UsersAdministratorDesktop3-視頻.avi"; copyFileWithBuffered(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("復(fù)制操作花費(fèi)的時(shí)間為:" + (end - start)); } //實(shí)現(xiàn)文件復(fù)制的方法 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造節(jié)點(diǎn)流 FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); //2.2造緩沖流 bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3.復(fù)制的細(xì)節(jié):讀取、寫(xiě)入 byte[] buffer = new byte[10]; int len; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.資源關(guān)閉 //要求:先關(guān)閉外層的流,再關(guān)閉內(nèi)層的流 if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //說(shuō)明:關(guān)閉外層流的同時(shí),內(nèi)層流也會(huì)自動(dòng)的進(jìn)行關(guān)閉,關(guān)于內(nèi)層流的關(guān)閉,可以省略 // fos.close(); // fis.close(); } } /* 使用BufferedReader和BufferedWriter實(shí)現(xiàn)文本文件的復(fù)制 */ @Test public void testBufferedReaderBufferedWriter(){ BufferedReader br = null; BufferedWriter bw = null; try { //創(chuàng)建文件和相應(yīng)的流 br = new BufferedReader(new FileReader(new File("dpcp.txt"))); bw = new BufferedWriter(new FileWriter(new File("dpcp1.txt"))); //讀寫(xiě)操作 //方式一:使用char[]數(shù)組 // 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){ //方法一: bw.write(data + " ");//data中不包含換行符 //方法二: bw.write(data);//data中不包含換行符 bw.newLine();//提供換行的操作 } } catch (IOException e) { e.printStackTrace(); } finally { //關(guān)閉資源 if(bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
處理流之二:轉(zhuǎn)換流的使用(重點(diǎn))
1.轉(zhuǎn)換流:屬于字符流
InputStreamReader:將一個(gè)字節(jié)的輸入流轉(zhuǎn)換為字符的輸入流
OutputStreamWriter:將一個(gè)字符的輸出流轉(zhuǎn)換為字節(jié)的輸出流
2.作用:提供字節(jié)流與字符流之間的轉(zhuǎn)換
3.解碼:字節(jié)、字節(jié)數(shù)組 ---> 字符數(shù)組、字符串
編碼:字符數(shù)組、字符串---> 字節(jié)、字節(jié)數(shù)組
說(shuō)明:編碼決定了解碼的方式
4.字符集
說(shuō)明:文件編碼的方式(比如:GBK),決定了解析時(shí)使用的字符集(也只能是GBK)
public class InputStreamReaderTest { /* 此時(shí)處理異常的話,仍然應(yīng)該使用try-catch-finally */ @Test public void test1() throws IOException{ FileInputStream fis = new FileInputStream("dbcp.txt"); // InputStreamReader isr = new InputStreamReader(fis);//使用系統(tǒng)默認(rèn)的字符集 //參數(shù)2指明了字符集,具體使用那個(gè)字符集,取決于文件dbcp.txt保存時(shí)使用的字符集 InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ String str = new String(cbuf,0,len); System.out.print(str); } isr.close(); } /* 此時(shí)處理異常的話,仍然應(yīng)該使用try-catch-finally 綜合使用InputStreamReader和OutputStreamWriter */ @Test public void test2() throws Exception{ //1.造文件、造流 File file1 = new File("dbcp.txt"); File file2 = new File("dbcp_gbk.txt"); FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk"); //2.讀寫(xiě)過(guò)程 char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ osw.write(cbuf,0,len); } //3.關(guān)閉資源 isr.close(); osw.close(); } }
3.其他流
1.標(biāo)準(zhǔn)的輸入、輸出流
1.1System.in:標(biāo)準(zhǔn)的輸入流,默認(rèn)從鍵盤(pán)輸入
System.out:標(biāo)準(zhǔn)的輸入流,默認(rèn)從控制臺(tái)輸出
1.2System類(lèi)的setIn() / setOut()方式重新指定輸入和輸出的流。
修改默認(rèn)的輸入和輸出行為:
System類(lèi)的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定輸入和輸出的流。
1.3練習(xí):
從鍵盤(pán)輸入字符串,要求將讀取道德整行字符串轉(zhuǎn)換成大寫(xiě)輸出。然后繼續(xù)進(jìn)行輸入操作。
直至當(dāng)輸入"e"或"exit"時(shí),退出程序
方法一:使用Scanner實(shí)現(xiàn),調(diào)用next()返回一個(gè)字符串
方法二:使用System.in實(shí)現(xiàn)。System.in ---> 轉(zhuǎn)換流 -->BufferedReader的readLine()
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("請(qǐng)輸入字符串:"); String data = br.readLine();//調(diào)用此方法讀取一行數(shù)據(jù) if("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){//避免空指針的寫(xiě)法,之前有 System.out.println("程序結(jié)束"); break; } String upperCase = data.toUpperCase(); System.out.println(upperCase); } } catch (IOException e) { e.printStackTrace(); } finally { if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
對(duì)象流 (重點(diǎn))
對(duì)象流的使用
1.ObjectInputStream和ObjectOutputStream
2.作用:用于存儲(chǔ)和讀取基本數(shù)據(jù)類(lèi)型或?qū)ο蟮奶幚砹鳌?br />
3.要想一個(gè)Java對(duì)象是可序列化的,需要滿足相應(yīng)的要求。見(jiàn)Person.java
4.序列化機(jī)制:(重點(diǎn)!!!?。?br />
對(duì)象序列化機(jī)制允許把內(nèi)存中的Java對(duì)象轉(zhuǎn)換成平臺(tái)無(wú)關(guān)的二進(jìn)制流,從而允許把這種二進(jìn)制流持久的保存在磁盤(pán)上,或通過(guò)網(wǎng)絡(luò)將這種
二進(jìn)制流傳輸?shù)搅硪粋€(gè)網(wǎng)絡(luò)節(jié)點(diǎn),當(dāng)其他程序獲取了這種二進(jìn)制流,就可以恢復(fù)成原來(lái)的Java對(duì)象
序列化過(guò)程:將內(nèi)存中的java對(duì)象保存到磁盤(pán)中或通過(guò)網(wǎng)絡(luò)傳輸出去 使用ObjectOutputStream實(shí)現(xiàn) @Test public void testObjectOutputStream(){ ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("object.dat")); oos.writeObject(new String("我愛(ài)北京天安門(mén)")); oos.flush();//刷新操作 oos.writeObject(new Person("王銘",23)); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if(oos != null){ try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } } 反序列化:將磁盤(pán)文件中的對(duì)象還原為內(nèi)存中的一個(gè)Java對(duì)象 使用ObjectInputStream來(lái)實(shí)現(xiàn) @Test public void testObjectInputStream(){ ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("object.dat")); Object obj = ois.readObject(); String str = (String) obj; Person p = ois.readObject(); System.out.println(str); System.out.println(p); }catch(IOException e){ e.printStackTrace(); }catch(ClassNotFoundException e){ e.printStackTrace(); }finally { if(ois != null){ ois.close; } } }
Person類(lèi)
Person需要滿足如下的要求,方可序列化
1.需要實(shí)現(xiàn)接口:Serializable
2.當(dāng)前類(lèi)提供一個(gè)全局常量:serialVersionUID
3.除了當(dāng)前Person類(lèi)需要實(shí)現(xiàn)Serializable接口之外,還必須保證其內(nèi)部所有屬性也必須是可序列化的(默認(rèn)情況下,基本數(shù)據(jù)類(lèi)型、String:本身是可序列化的)
補(bǔ)充:ObjectOutputStream 和 ObjectInputStream不能序列化static和transient修飾的成員變量
eg:輸出結(jié)果:Person{name="null",age=0,id=0,acct=null}
public class Person implements Serializable{ public static final long serialVersionUID = 397497937034L; private String name; private int age; @Override public String toString() { return "Person{" + "name="" + name + """ + ", age=" + age + "}"; } 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() { } }
對(duì)象的序列化機(jī)制
隨機(jī)存取文件流(了解)
RandomAccessFile 1.RandomAccessFile直接繼承于java.lang.Object類(lèi),實(shí)現(xiàn)了DataInput和DataOutput接口 2.RandomAccessFile既可以作為一個(gè)輸入流,又可以作為一個(gè)輸出流 3.如果RandomAccessFile作為輸出流時(shí),寫(xiě)出到的文件如果不存在,則在執(zhí)行過(guò)程中自動(dòng)創(chuàng)建 如果寫(xiě)出到的文件存在,則會(huì)對(duì)原有文件內(nèi)容進(jìn)行覆蓋,(默認(rèn)情況下,從頭覆蓋) 4.可以通過(guò)相關(guān)的操作,實(shí)現(xiàn)RandomAccessFile"插入"數(shù)據(jù)的效果 public abstract class RandomAccessFileTest { @Test public void test1(){ RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try { raf1 = new RandomAccessFile(new File("愛(ài)情與友情.jpg"), "r"); raf2 = new RandomAccessFile(new File("愛(ài)情與友情1.jpg"), "rw"); byte[] buffer = new byte[1024]; int len; while((len = raf1.read(buffer)) != -1){ raf2.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(raf1 != null){ try { raf1.close(); } catch (IOException e) { e.printStackTrace(); } } if(raf2 != null){ try { raf2.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void test2()throws IOException{ RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw"); raf1.seek(3);//將指針調(diào)到角標(biāo)為3的位置 raf1.write("xyz".getBytes());// raf1.close(); } 使用RandomAccessFile實(shí)現(xiàn)數(shù)據(jù)的插入效果 @Test public void test3() throws IOException{ RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw"); raf1.seek(3);//將指針調(diào)到角標(biāo)為3的位置 //保存指針3后面的所有數(shù)據(jù)到StringBuilder中 StringBuilder builder = new StringBuilder((int) new File("hello.txt".length())); byte[] buffer = new byte[20]; int len; while((len = raf1.read(buffer)) != -1){ builder.append(new String(buffer,0,len)); } //調(diào)回指針,寫(xiě)入"xyz" raf1.seek(3); raf1.write("xyz".getBytes()); //將StringBuilder中的數(shù)據(jù)寫(xiě)入到文件中 raf1.write(builder.toString().getBytes()); raf1.close(); } }
Java中的NIO
到此這篇關(guān)于Java深入淺出說(shuō)流的使用的文章就介紹到這了,更多相關(guān)Java流內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_49329785/article/details/119900357