文件操作
Java流簡介
文件File的使用
FileOutputStream和FileInputStream的使用
FileWriter和FileReader的使用
ObjectOutputStream和ObjectInputStream的使用
BufferedOutputStream和BufferedInputStream的使用
BufferedWriter和BufferedReader的使用
PrintStream和PrintWriter的使用
一.Java流(Stream)
Java.io 包幾乎包含了所有操作輸入、輸出需要的類。所有這些流類代表了輸入源和輸出目標。
流Stream,封裝數(shù)據(jù)的寫入寫出,統(tǒng)一管理數(shù)據(jù)的寫入和讀取
一個流可以理解為一個數(shù)據(jù)的序列。流的方向,參考的是自己的內(nèi)存空間-代碼的位置是內(nèi)存空間。
輸出流:從內(nèi)存空間將數(shù)據(jù)寫到外部。
輸入流:將外部數(shù)據(jù)寫到內(nèi)存中。
粉紅色是類型歸納,綠色是接口,黃色是類
字節(jié)流類型通過byte[]數(shù)組,接受數(shù)據(jù)或者保存數(shù)據(jù)。
字符流類型通過char[]數(shù)組,接受數(shù)據(jù)或者保存數(shù)據(jù)。
二.文件File
1.構(gòu)造方法
//通過將給定的路徑名字符串轉(zhuǎn)換為抽象路徑名來創(chuàng)建 File(String pathname) //從父抽象路徑名和子路徑名字符串創(chuàng)建 File(File parent, String child) //從父路徑名字符串和子路徑名字符串創(chuàng)建 File(String parent, String child) //通過將給定的 file: URI轉(zhuǎn)換為抽象路徑名來創(chuàng)建 File(URL uri)2.具體的方法
- 測試此抽象路徑名表示的文件或目錄是否存在。
public boolean exists()
- 當且僅當具有該名稱的文件尚不存在時,原子地創(chuàng)建一個由該抽象路徑名命名的新的空文件。
public boolean createNewFile() throws IOException
- 測試此抽象路徑名表示的文件是否為目錄。
public boolean isDirectory()
- 測試此抽象路徑名表示的文件是否為普通文件。
public boolean isFile()
- 刪除由此抽象路徑名表示的文件或目錄。 如果此路徑名表示目錄,則目錄必須為空才能刪除。
public boolean delete()
- 創(chuàng)建由此抽象路徑名命名的目錄。
public boolean mkdir()
- 創(chuàng)建由此抽象路徑名命名的目錄,包括任何必需但不存在的父目錄。請注意,如果此操作失敗,它可能已成功創(chuàng)建一些必需的父目錄。
public boolean mkdirs()
- 返回一個抽象路徑名數(shù)組,表示由該抽象路徑名表示的目錄中的文件。如果此抽象路徑名不表示目錄,則此方法返回null 。
public File[] listFiles()
- 返回一個抽象路徑名數(shù)組,表示由此抽象路徑名表示的滿足指定過濾器的目錄中的文件和目錄。
public File[] listFiles(FilenameFilter filter)
- 創(chuàng)建例子
String path = "G:/Android_Studio"; //方式1 File file = new File(path.concat("/1.txt")); //方式2 File file = new File(path,"1.txt"); //判斷是否存在 if (file.exists() == false){ //不存在就創(chuàng)建 file.createNewFile(); }
三.FileOutputStream和FileInputStream的使用
FileOutputStream
1.構(gòu)造方法
第二個參數(shù)默認是false,寫入是覆蓋寫入;true表示追加方式寫入。
//創(chuàng)建文件輸出流以指定的名稱寫入文件。 FileOutputStream(String name) //創(chuàng)建文件輸出流以指定的名稱寫入文件。 FileOutputStream(String name, boolean append) // 創(chuàng)建文件輸出流以寫入由指定的 File對象表示的文件。 FileOutputStream(File file) //創(chuàng)建文件輸出流以寫入由指定的 File對象表示的文件 FileOutputStream(File file, boolean append)2.寫入數(shù)據(jù)方法
//將 b.length字節(jié)從指定的字節(jié)數(shù)組寫入此文件輸出流。 public void write(byte[] b) throws IOException //從位于偏移量 off的指定字節(jié)數(shù)組寫入 len字節(jié)到該文件輸出流。 public void write(byte[] b int off, int len) throws IOException3.關(guān)閉連接方法
//關(guān)閉此文件輸出流并釋放與此流相關(guān)聯(lián)的任何系統(tǒng)資源。 此文件輸出流可能不再用于寫入字節(jié)。 public void close() throws IOException4.清空流,把緩沖區(qū)的內(nèi)容強制的寫出
flush
FileInputStream
1.構(gòu)造方法
//通過打開與實際文件的連接來創(chuàng)建一個 FileInputStream //該文件由文件系統(tǒng)中的路徑名 name命名。 FileInputStream(String name) // 通過打開與實際文件的連接創(chuàng)建一個 FileInputStream //該文件由文件系統(tǒng)中的 File對象 file命名。 FileIntputStream(File file)2.讀取數(shù)據(jù)方法
//返回值是讀取到緩沖區(qū)的總字節(jié)數(shù);如果為-1,達到文件末尾 //從該輸入流讀取最多b.length字節(jié)的數(shù)據(jù)到字節(jié)數(shù)組。 public int read(byte[] b) throws IOException //從該輸入流讀取最多l(xiāng)en字節(jié)的數(shù)據(jù)到字節(jié)數(shù)組,起始索引從off開始。 public int read(byte[] b int off,int len) throws IOException3.關(guān)閉連接方法
//關(guān)閉此文件輸入流并釋放與流相關(guān)聯(lián)的任何系統(tǒng)資源。 // 如果該流具有相關(guān)聯(lián)的信道,則該信道也被關(guān)閉。 public void close() throws IOException
FileOutputStream和FileInputStream的具體使用
String path = "G:/Android_Studio/AndroidStudioProjects/JavaCode/Java/src/main/java/swu/xl/day8/Base"; File file = new File(path.concat("/1.txt")); //判斷是否存在 if (file.exists() == false){ //不存在就創(chuàng)建 file.createNewFile(); } //1.創(chuàng)建文件輸出流對象 FileOutputStream fos = new FileOutputStream(file); //2.調(diào)用write方法寫入 byte[] bytes = {'a','b','c'}; fos.write(bytes); //3.把緩沖區(qū)的內(nèi)容強制寫出,確保緩沖區(qū)沒有東西 fos.flush(); //4.操作完畢需要關(guān)閉Stream對象 fos.close(); FileInputStream fis = new FileInputStream(file); //2.調(diào)用read方法寫入 byte[] names = new byte[12]; int count = fis.read(names); fis.close(); System.out.println(count+" "+(new String(names)));
四.FileWriter和FileReader的使用
FileWriter
1.構(gòu)造方法
第二個參數(shù)默認是false,寫入是覆蓋寫入;true表示追加方式寫入。
//構(gòu)造一個給定文件名的FileWriter對象。 FileWriter(String fileName) //構(gòu)造一個給定文件名的FileWriter對象。 FileWriter(String fileName, boolean append) //給一個File對象構(gòu)造一個FileWriter對象。 FileWriter(File file) //給一個File對象構(gòu)造一個FileWriter對象。 FileWriter(File file, boolean append)2.寫入數(shù)據(jù)方法
//寫入字符數(shù)組 public void write(char[] cbuf) throws IOException //寫入字符數(shù)組的一部分。 public void write(char[] cbuf,int off,int len) throws IOException // 寫一個字符串 public void write(String str) throws IOException // 寫一個字符串的一部分。 public void write(String str, int off, int len) throws IOException3.關(guān)閉連接方法
//關(guān)閉此文件輸出流并釋放與此流相關(guān)聯(lián)的任何系統(tǒng)資源。 此文件輸出流可能不再用于寫入字節(jié)。 public void close() throws IOException4.清空流,緩沖區(qū)的內(nèi)容強制的寫出
flush
FileReader
1.構(gòu)造方法
//創(chuàng)建一個新的 FileReader ,給定要讀取的文件的名稱。 FileReader(String name) //創(chuàng)建一個新的 FileReader ,給出 File讀取。 FileIReader(File file)2.讀取數(shù)據(jù)方法
//將字符讀入數(shù)組 public int read(char[] cbuf) throws IOException //將字符讀入數(shù)組的一部分。 public int read(char[] cbuf, int offset, int length) throws IOException3.關(guān)閉連接方法
//關(guān)閉此文件輸入流并釋放與流相關(guān)聯(lián)的任何系統(tǒng)資源。 // 如果該流具有相關(guān)聯(lián)的信道,則該信道也被關(guān)閉。 public void close() throws IOException
FileWriter和FileReader的具體使用
String path = "G:/Android_Studio/AndroidStudioProjects/JavaCode/Java/src/main/java/swu/xl/day8/Base"; File file = new File(path.concat("/1.txt")); //判斷是否存在 if (file.exists() == false){ //不存在就創(chuàng)建 file.createNewFile(); } //1.創(chuàng)建文件輸出流對象 FileWriter fw = new FileWriter(file); //2.調(diào)用write方法寫入 char[] name = {'安','桌','開','發(fā)'}; fw.write(name); //String string = new String("sac"); //fw.write(string); //3.把緩沖區(qū)的內(nèi)容強制寫出,確保緩沖區(qū)沒有東西 fw.flush(); //4.操作完畢需要關(guān)閉Stream對象 fw.close(); FileReader fr = new FileReader(file); char[] book = new char[4]; count = fr.read(book); fr.close(); System.out.println(count+" "+(new String(book)));
五.ObjectOutputStream和ObjectInputStream
ObjectOutputStream和ObjectInputStream用于向文件中寫入對象,類似于iOS的NSKeyedArchiver和NSKeyedUnarchiver對數(shù)據(jù)的歸檔和解檔。類比iOS對自定義的類創(chuàng)建出來的對象進行歸檔,我們需要先實現(xiàn)
NSCoding協(xié)議。Java里面需要對自定義的類實現(xiàn)
serializable接口實現(xiàn)序列化,該接口沒有任何方法。如果自定義的類內(nèi)部還有屬性變量是其他自定義的類的對象,這個類也必須實現(xiàn)
Seriablizable接口
ObjectOutputStream和ObjectInputStream都需要傳入一個OutputStream和InputStream類型的對象,它們是抽象類,所以使用子類FileOutputStream和FileInputStream來實現(xiàn)初始化。具體使用
//序列化好的類 import java.io.Serializable; public class Person implements Serializable { String name; int age; } //file和之前的例子相同 //具體寫入 Person xw = new Person(); xw.name = "小王"; xw.age = 18; OutputStream os = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(xw); oos.close(); //具體讀取 InputStream is = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(is); Person xw = (Person) ois.readObject(); System.out.println(xw.name+" "+xw.age); ois.close();
六.BufferedOutputStream和BufferedInputStream
BufferedOutputStream和BufferedInputStream類的構(gòu)造函數(shù)都需要傳入一個OutputStream或InputStream類型的對象,它們是抽象類,所以使用子類FileOutputStream或FileInputStream來實現(xiàn)初始化。數(shù)據(jù)覆蓋寫入的意思是下一次運行寫入是覆蓋寫入,
RandomAccessFile有類似于C語言文件操作中seek,如果你想要可以讀取文件的任意位置可以使用它。具體使用:將圖片復(fù)制到指定位置。
//1.源文件的路徑 String sourcePath = "C:/Users/a2867/Desktop/壁紙/1.jpg"; //2.目標文件的路徑 String desPath = "C:/Users/a2867/Desktop/1.jpg"; FileInputStream fis = new FileInputStream(sourcePath); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream(desPath); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] in = new byte[1024]; int count = 0; while((count = bis.read(in)) != -1){ bos.write(in,0,count); } bis.close(); bos.flush(); bos.close();
七.BufferedWriter和BufferedReader的使用
BufferedWriter和BufferedReader類的構(gòu)造函數(shù)都需要傳入一個OutputStreamWriter或InputStreamReader類型的對象。
OutputStreamWriter和InputStreamReader類的構(gòu)造函數(shù)都需要傳入一個OutputStream或InputStream類型的對象。
public readLine() throws IOException讀一行文字。 一行被視為由換行符('\ n'),回車符('\ r')中的任何一個或隨后的換行符終止。具體使用:將圖片復(fù)制到指定位置。
//1.源文件的路徑 String sourcePath = "C:/Users/a2867/Desktop/壁紙/1.jpg"; //2.目標文件的路徑 String desPath = "C:/Users/a2867/Desktop/1.jpg"; FileInputStream fis = new FileInputStream(sourcePath); BufferedReader bis = new BufferedReader(new InputStreamReader(fis)); FileOutputStream fos = new FileOutputStream(desPath); BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(fos)); char[] in = new char[1024]; int count = 0; while((count = bis.read(in)) != -1){ bos.write(in,0,count); } bis.close(); bos.flush(); bos.close(); //結(jié)果不對,對于這種圖片,視頻等操作建議使用字節(jié)流方式,不然很可能出錯具體使用:讀取控制臺輸入(Java 的控制臺輸入由 System.in 完成)
public class BRReadLines { public static void main(String args[]) throws IOException { // 使用 System.in 創(chuàng)建 BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'end' to quit."); do { str = br.readLine(); System.out.println(str); } while (!str.equals("end")); } } 輸出: Enter lines of text. Enter 'end' to quit. This is line one This is line one This is line two This is line two end end
八.PrintStream和PrintWriter的使用
PrintStream
Java的控制臺的輸出由
print()和println()完成。這些方法都由類PrintStream定義,System.out是該類對象的一個引用。
PrintStream繼承了OutputStream類,并且實現(xiàn)了方法write()。這樣,write()也可以用來往控制臺寫操作。
write()方法不經(jīng)常使用,因為print()和println()方法用起來更為方便。
format()使用指定的格式字符串和參數(shù)將格式化的字符串寫入此輸出流。
append()將指定的字符或者字符序列附加到此輸出流。
checkError()刷新流并檢查其錯誤狀,因為該輸出流不會拋異常。
clearError()清除此流的內(nèi)部錯誤狀態(tài)。。
flush()刷新流。
close()關(guān)閉流。具體使用:向控制臺輸出
public class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); } } 輸出: APrintWriter
構(gòu)造方法:
public PrintWriter(Writer out,boolean autoFlush)其他方法和PrintStream類似
PrintStream和PrintWriter的區(qū)別
PrintStream操縱的是字節(jié)流,PrintWriter操縱的是字符流。
PrintStream在遇到換行符的時候就會自動刷新,即在調(diào)用了println()方法,或者文本中出現(xiàn)“\n”,就會自動flush。
PrintWriter需要在構(gòu)造方法中設(shè)置自動刷新,或者手動flush。
