目錄
一、File 類
二、IO流
三、位元組輸出流
四、位元組輸入流
五、位元組流檔案復制
六、字符輸出流
七、字符輸入流
八、字符流復制文本檔案
一、File 類
1. 概述
檔案 和 目錄路徑名 的抽象表達形式
Java中把檔案或者目錄(檔案夾)都封裝成 File物件
我們要去操作硬碟上的檔案,或者檔案夾只要找到 File這個類即可
File類物件,只是路徑名的 抽象表示形式,即使該檔案在作業系統上并不物理存在,也可以創建這個路徑所表示的File物件
2. 構造方法
File(String pathname):通過給定 路徑名字串 轉換為 抽象路徑名 來創建一個新 File 實體
windows中的路徑或檔案名不區分大小寫,但是最好別這樣,跨平臺可能會出現問題
File(String parent, String child):根據 parent 路徑名字串 和 child 路徑名字串,創建一個新 File 實體
好處: 單獨操作父路徑和子路徑
File(File parent, String child):根據 parent 抽象路徑名 和 child 路徑名字串,創建一個 File 實體
好處: 父路徑是File型別,父路徑可以直接呼叫File類方法
public class Test {
public static void main(String[] args) {
/*
* File(String pathname)
* 傳遞路徑名: 可以寫到檔案夾,可以寫到一個檔案
*/
File file = new File("f:\\a.txt");
System.out.println(file);
/*
* File(String parent, String child)
* 傳遞字串父路徑,字串子路徑
*/
File file = new File("f:\\", "a.txt");
System.out.println(file);
/*
* File(File parent, String child)
* 傳遞傳遞File型別父路徑,字串子路徑
*/
File parent = new File("f:");//帶不帶"\\"都可以
File file = new File(parent, "a.txt");
System.out.println(file);
}
}
3. File 類成員方法
—創建功能—
public boolean createNewFile():創建檔案,如果檔案已存在,不再創建
public boolean mkdir():創建單級檔案夾,如果檔案夾已存在,不再創建
public boolean mkdirs():創建多級檔案夾,檔案夾已經存在了,不在創建
mkdirs() 也可以創建單級檔案夾,所以推薦使用 mkdirs()
—洗掉功能—
public boolean delete(): 洗掉檔案或者檔案夾,不走回收站,直接從硬碟洗掉!
如果此路徑名表示一個目錄,則該目錄 必須為空 才能洗掉,
—重命名功能—
public boolean renameTo(File dest): 重新命名檔案
—判斷功能—
public boolean isFile() :判斷File構造方法中封裝的路徑是不是檔案
public boolean isDirectory():判斷File構造方法中封裝的路徑是不是檔案夾
public boolean exists(): 判斷File構造方法中封裝的路徑是否存在
public boolean canRead() :讀權限
public boolean canWrite() :寫權限
public boolean isHidden() :是否隱藏
—基本獲取功能—
public String getAbsolutePath():獲取絕對路徑,回傳 String 物件
public File getAbsoluteFile():獲取絕對路徑,回傳 file 物件(推薦使用)
eclipse和 IDEA環境中,寫一個相對路徑,獲取的絕對位置是工程根目錄
public String getPath():將抽象路徑名轉換為字串(就相當于 toString)
public String getName():回傳路徑中表示的檔案名或者檔案夾名 (獲取路徑中的最后部分的名字)
public long length() :回傳路徑中表示的檔案的位元組數(檔案夾為 0)
public long lastModified() :上次修改的時間
String getParent(): 獲取父路徑,回傳String物件
File getParentFile(): 獲取父路徑,回傳File物件(推薦使用)
4. File類高級獲取功能
public String[] list()
獲取到 File 構造方法中封裝的路徑中的檔案和檔案夾名 (遍歷一個目錄),回傳只有名字,如果此抽象路徑名不表示一個目錄,那么此方法將回傳 nul,回傳的是一個字串陣列,不會遞回的獲取子目錄中的資訊(檔案或者目錄的名稱),
public File[] listFiles()
獲取到 File 構造方法中封裝的路徑中的檔案和檔案夾名 (遍歷一個目錄),回傳的是目錄或者檔案的 全路徑
回傳一個 File物件陣列,不會遞回的獲取子目錄中的資訊(檔案或者目錄的名稱)
注意:在獲取指定目錄下的檔案或者檔案夾時必須滿足下面兩個條件
1)指定的目錄必須存在
2)指定的必須是目錄,否則容易引發 回傳陣列為null,出現NullPointerException
5. 檔案過濾器
listFiles(FileFilter filter) : 傳遞 FileFilter 介面的實作類
FileFilter 介面:
必須自定義 FileFilter 介面實作類,重寫抽象方法,然后將介面實作類物件傳遞到遍歷方法 listFiles
boolean accept(File pathname) 回傳 true 滿足條件,回false不滿足過濾條件
過濾器中的 accept() 方法接受一個引數,這個引數就當前檔案或檔案夾物件(全路徑)
FilenameFilter介面:
過濾器中的 accept() 接受兩個引數,一個當前檔案或檔案夾所在的路徑,一個是當前檔案或檔案夾物件的名稱
boolean accept(File dir, String name) 回傳true滿足條件,回false不滿足過濾條件
當我們需要過濾檔案名稱時就可以使用 FilenameFilter 這個過濾器,當我們想對當前檔案或檔案夾進行過濾,就可以使用 FileFilter
對于一個目錄下,檔案或檔案目錄的篩選作業代碼:
不變——篩選程序
變化——篩選條件
原理分析
listFiles() 遍歷目錄的同時,獲取到了檔案名全路徑,呼叫過濾器的方法 accept(),將獲取到的路徑傳遞給 accept(),accept() 方法接收了引數,引數是 listFiles 傳遞來的,在 accept()方法中,進行判斷,如果滿足過濾條件,回傳true,否則回傳false,一旦方法回傳了true,listFiles 就將路徑保存到 File陣列 中
6. 遞回遍歷全目錄
public class FileDemo {
public static void main(String[] args) {
File dir = new File("E:\\a");
getAllDir(dir);
}
// 定義方法,實作目錄的全遍歷
private static void getAllDir(File dir) {
//呼叫方法listFiles()對目錄,dir進行遍歷
File[] fileArr = dir.listFiles();
for(File f : fileArr){
//判斷變數f表示的路徑是不是檔案夾,是,則遞回遍歷
if(f.isDirectory()){
getAllDir(f);
}else{
System.out.println(f);
}
}
}
}
二、IO流
1. 概述
IO流用來處理設備之間的 資料傳輸
Java對資料的操作是通過 流 的方式
Java用于操作流的物件都在 IO包 中(input/output)
Output操作:把記憶體中的資料存盤到持久化設備上這個動作稱為輸出(寫)
Input操作:把持久設備上的資料讀取到記憶體中的這個動作稱為輸入(讀)
流的分類:
流按流向分為兩種:
輸出流:記憶體——>外設(寫出資料)
輸入流:磁盤——>記憶體(讀入資料)
流按操作型別分為兩種:
位元組流:位元組流可以操作任何資料,因為在計算機中任何資料都是以位元組的形式存盤的
字符流:字符流只能操作純字符資料,比較方便,
2. IO流常用父類
位元組流的抽象父類:InputStream ,OutputStream
字符流的抽象父類:Reader , Writer
三、位元組輸出流
1. 概述
java.io.OutputStream 此抽象類,是表示輸出位元組流的所有類的超類,操作的資料都是 位元組
2. OutputStream 的核心方法:
void close(): 關閉此輸出流并釋放與此流有關的所有系統資源,
close的常規協定:該方法將關閉輸出流,關閉的流不能執行輸出操作,也不能重新打開,
如果流物件建立失敗了,需要關閉資源嗎?
new 物件的時候,失敗了,沒有占用系統資源;釋放資源的時候,對流物件判斷null,變數不是null,物件建立成功,需要關閉資源
write(byte[] b): 將 b.length 個位元組從指定的 byte 陣列寫入此輸出流
write(byte[] b, int off, int len):將指定 byte 陣列中從偏移量 off 開始的 len 個位元組寫入此輸出流,
write(int b): 將指定的位元組寫入此輸出流,write 的常規協定:向輸出流寫入一個位元組,要寫入的位元組是引數 b 的八個低位,b 的 24 個高位將被忽略,
3. FileOutputStream 類
(1) 構造方法
FileOutputStream(File file) :創建一個向指定 File 物件表示的檔案中寫入資料的檔案輸出流,
FileOutputStream(File file, boolean append): 創建一個向指定 File 物件表示的檔案中寫入資料的檔案輸出流,以追加的方式寫入,
FileOutputStream(String name) :創建一個向具有指定名稱的檔案中寫入資料的輸出檔案流,
FileOutputStream(String name, boolean append) :創建一個向具有指定 name 的檔案中寫入資料的輸出檔案流,以追加的方式寫入,
(2) 流物件的使用步驟:
創建流子類的物件,系結資料目的
呼叫流物件的方法write寫
close釋放資源
注意事項:流物件的構造方法,可以創建檔案,如果檔案存在,直接覆寫
public class IoDemo {
public static void main(String[] args) throws IOException {
//創建流子類的物件,系結資料目的
FileOutputStream fos = new FileOutputStream("E:\\a.txt");
//用write方法寫資料
//寫一個位元組
fos.write(100); //d
//寫位元組陣列
byte[] bytes = {65,66,67,68}; //ABCD
fos.write(bytes);
//寫位元組的一部分,開始索引,寫幾個
fos.write(bytes,1,1); //B
//寫入位元組陣列的簡便方式
//寫字串
fos.write("Hello".getBytes());
//關閉資源
fos.close();
}
}
4. 檔案的續寫和換行
(1)實作資料的換行
在檔案中,寫入換行符號換行: \r\n
\r\n 可以寫在上一行的末尾, 也可以寫在下一行的開頭
fos.write("hello\r\n".getBytes());
(2)關于資料的追加寫入
默認情況下,當一個檔案輸出流物件,指向一個檔案的時候,會清空檔案內容
必須使用特殊的構造方法實作檔案的追加寫入,FileOutputStream構造方法, 的第二個引數中加入 true
//實作追加寫入:
FileOutputStream fos = new FileOutputStream(file, true);
5. IO例外的處理
一些細節:
保證流物件變數,作用域足夠
catch里面處理例外
輸出例外的資訊,目的看到哪里出現了問題,停下程式,從新嘗試
如果流物件建立失敗了,需要關閉資源嗎
new 物件的時候,失敗了,沒有占用系統資源;釋放資源的時候,對流物件判斷 null;變數不是 null,物件建立成功,需要關閉資源
public class FileOutputStreamDemo3 {
public static void main(String[] args) {
File file = new File("c:\\file.txt");
//try 外面宣告變數,try 里面建立物件,為了提升流物件作用域
//定義FileOutputStream的參考
FileOutputStream fos = null;
try {
//創建FileOutputStream物件
fos = new FileOutputStream(file);
//寫出資料
fos.write("abcde".getBytes());
} catch (IOException e) {
System.out.println(e.toString() + "----");
throw new RuntimeException("檔案寫入失敗,重試");
} finally {
//一定要判斷fos是否為null,只有不為null時,才可以關閉資源
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException("關閉資源失敗");
}
}
}
}
}
四、位元組輸入流
1. 概述
java.io.InputStream: 此抽象類是表示位元組輸入流的所有類的超類,讀取任意檔案,每次只讀取1個位元組
2. 核心方法
abstract int read():讀取一個位元組
read()方法的特點:read() 執行一次,就會自動讀取下一個位元組,回傳值是讀取到的位元組, 讀取到結尾回傳 -1
public class IoDemo {
public static void main(String[] args) throws IOException {
//創建位元組輸入流的子類物件
FileInputStream fis = new FileInputStream("E:\\a.txt"); //ABCD
//讀取一個位元組,呼叫read方法,回傳int
//使用回圈方式,讀取檔案,回圈結束的條件:read() 回傳 -1
int len = 0; //接收read()的回傳值
while((len = fis.read()) != -1){
System.out.print((char)len); //可以轉換成字符
}
//關閉資源
fis.close();
}
}
int read(byte[] b):讀取一定數量的位元組,并將其存盤在緩沖區陣列 b 中
int read(byte[] b, int off, int len) :讀取最多 len 個位元組,存入 byte 陣列,
陣列的作用:緩沖的作用, 提高效率
read 回傳的 int,表示讀取到多少個有效的位元組數
public class IoDemo {
public static void main(String[] args) throws IOException {
//創建位元組輸入流的子類物件
FileInputStream fis = new FileInputStream("E:\\a.txt");
//創建位元組陣列
byte[] b = new byte[1024];
int len = 0;
while((len = fis.read(b)) != -1){
System.out.print(new String(b,0,len)); //使用String的構造方法,轉為字串
}
//關閉資源
fis.close();
}
}
3. FileInputStream 類
(1)構造方法
為這個流物件 系結資料源
FileInputStream(File file)
FileInputStream(String name)
引數:File物件 和 String物件
(2)輸入流讀取檔案的步驟
創建位元組輸入流的子類物件
呼叫讀取方法 read 讀取
關閉資源
(3)讀取資料的方式:
第一種方式:一次讀取一個位元組資料
第二種方式:一次讀取一個位元組陣列
第二種方式效率更高,每次讀取都會和作業系統發生一次互動,第二種方式每次可以讀取多個資料,提高了操作效率
4、釋放資源的另一種方式
//1.第一種釋放資源的方式 closeQuietly
//釋放輸入流資源
closeQuietly(fis);
//釋放輸出流物件
closeQuietly(fos);
private static void closeQuietly(Closeable close) {
if(close != null) {
try {
close.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//2.jdk7 中引入的 try-with-resource陳述句
try(放申請資源的陳述句){
}catch() {
}
// 一旦資源的申請放在try-with-resource陳述句的()中,那么資源會保證一定自動被釋放
五、位元組流檔案復制
1. 讀取單個位元組
public class Copy {
public static void main(String[] args) {
long s = System.currentTimeMillis();
//定義兩個流的物件變數
FileInputStream fis = null;
FileOutputStream fos = null;
try{
//建立兩個流的物件,系結資料源和資料目的
fis = new FileInputStream("D:\\test.mp3"); //8,003,733 位元組
fos = new FileOutputStream("d:\\test.mp3");
//位元組輸入流,讀取1個位元組,輸出流寫1個位元組
int len = 0 ;
while((len = fis.read())!=-1){
fos.write(len);
}
}catch(IOException e){
System.out.println(e);
throw new RuntimeException("檔案復制失敗");
}finally{
try{
if(fos!=null)
fos.close();
}catch(IOException e){
throw new RuntimeException("釋放資源失敗");
}finally{
try{
if(fis!=null)
fis.close();
}catch(IOException e){
throw new RuntimeException("釋放資源失敗");
}
}
}
long e = System.currentTimeMillis();
System.out.println(e-s);
}
}
//耗時:61817
2. 讀取位元組陣列
public class Copy_1 {
public static void main(String[] args) {
long s = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream("D:\\test.mp3");
fos = new FileOutputStream("E:\\test.mp3");
//定義位元組陣列,緩沖
byte[] bytes = new byte[1024*10];
//讀取陣列,寫入陣列
int len = 0 ;
while((len = fis.read(bytes))!=-1){
fos.write(bytes, 0, len);
}
}catch(IOException e){
System.out.println(e);
throw new RuntimeException("檔案復制失敗");
}finally{
try{
if(fos!=null)
fos.close();
}catch(IOException e){
throw new RuntimeException("釋放資源失敗");
}finally{
try{
if(fis!=null)
fis.close();
}catch(IOException e){
throw new RuntimeException("釋放資源失敗");
}
}
}
long e = System.currentTimeMillis();
System.out.println(e-s);
}
}
//耗時:41
六、字符輸出流
1. 概述
java.io.Writer 所有字符輸出流的超類,寫檔案,寫 文本檔案
2. 方法介紹
void write(int c):寫入單個字符
void write(String str) :寫入字串
void write(String str, int off, int len):寫入字串的某一部分
void write(char[] cbuf):寫入字符陣列
abstract void write(char[] cbuf, int off, int len) :寫入字符陣列的某一部分
3. FileWriter 類
Writer 類是抽象類,找到子類物件 FileWriter
構造方法:引數也是 File 型別物件 和 String 檔案名
字符輸出流,寫資料的時候,必須要運行一個功能,重繪功能:flush()
public class WriterDemo {
public static void main(String[] args) throws IOException{
FileWriter fw = new FileWriter("c:\\1.txt");
//寫1個字符
fw.write(100);
fw.flush();
//寫1個字符陣列
char[] c = {'a','b','c','d','e'};
fw.write(c);
fw.flush();
//寫字符陣列一部分
fw.write(c, 2, 2);
fw.flush();
//寫如字串
fw.write("hello");
fw.flush();
fw.close();
}
}
七、字符輸入流
1. 概述
java.io.Reader,字符輸入流讀取文本檔案,所有字符輸入流的超類,專門讀取文本檔案
2. 方法介紹
int read(): 讀取單個字符
int read(char[] cbuf):將字符讀入陣列
abstract int read(char[] cbuf, int off, int len) :將字符讀入陣列的某一部分
沒有讀取字串的方法
3. FileReader 類
Reader類 是抽象類,找到子類物件 FileReader
構造方法:寫入的資料目的,系結資料源,引數也是 File 型別物件 和 String 檔案名
public class ReaderDemo {
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("c:\\1.txt");
//讀字符
/*int len = 0 ;
while((len = fr.read())!=-1){
System.out.print((char)len);
}*/
//讀陣列
char[] ch = new char[1024];
int len = 0 ;
while((len = fr.read(ch))!=-1){
System.out.print(new String(ch,0,len)); //轉字串
}
fr.close();
}
}
4. flush 方法和 close 方法區別
flush()方法:用來重繪緩沖區的,重繪后可以再次寫出,只有字符流才需要重繪
close()方法:用來關閉流釋放資源的的,如果是帶緩沖區的流物件的close()方法,不但會關閉流,還會再關閉流之前重繪緩沖區,關閉后不能再寫出
八、字符流復制文本檔案
字符流復制文本檔案,必須是文本檔案
字符流查詢本機默認的編碼表,簡體中文GBK
FileReader 讀取資料源
FileWriter 寫入到資料目的
//讀取字符陣列
public class Copy_2 {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try{
fr = new FileReader("c:\\1.txt");
fw = new FileWriter("d:\\1.txt");
char[] cbuf = new char[1024];
int len = 0 ;
while(( len = fr.read(cbuf))!=-1){
fw.write(cbuf, 0, len);
fw.flush();
}
}catch(IOException ex){
System.out.println(ex);
throw new RuntimeException("復制失敗");
}finally{
try{
if(fw!=null)
fw.close();
}catch(IOException ex){
throw new RuntimeException("釋放資源失敗");
}finally{
try{
if(fr!=null)
fr.close();
}catch(IOException ex){
throw new RuntimeException("釋放資源失敗");
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/229157.html
標籤:java
上一篇:JAVA-泛型
