日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java学习之文件操作

發(fā)布時間:2025/3/15 java 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java学习之文件操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

因為文件操作是一個非常常見的操作,在加上用法非常固定,就寫一篇博客整理一下
我直接用一個小項目說明文件操作的方法,當然主要還是去看官方的api文檔是最好的
我的一個demo程序是監(jiān)聽一個目錄下的所有文件,把每一個讀取每一個文件的內容,然后再將其復制到另外一個目錄下。

本博客原創(chuàng),轉載請注明!!!
本文鏈接
個人博客:https://ronglin.fun/?p=143
PDF鏈接:見博客網站
CSDN: https://blog.csdn.net/RongLin02/article/details/118736944

以下實操均是我自己寫的小demo,如有錯誤請聯系我!
查詢的API內容來自以下網站,僅用于學習,如有侵權請聯系我刪除
一個中文API:MaTools在線中文API-JDK8

File類

對于文件的操作,我一般用File類,對于文件本身內容的操作,一般用輸入輸出流來完成。
有兩個概念是要知道的,一個是絕對路徑,還有一個是相對路徑。

常用方法

1.構造方法

//從父抽象路徑名和子路徑名字符串創(chuàng)建新的 File實例。 File(File parent, String child)//通過將給定的路徑名字符串轉換為抽象路徑名來創(chuàng)建新的 File實例。 File(String pathname)//從父路徑名字符串和子路徑名字符串創(chuàng)建新的 File實例。 File(String parent, String child)//通過將給定的 file: URI轉換為抽象路徑名來創(chuàng)建新的 File實例。 File(URI uri)

一共四種構造方法,可根據需要選擇不同的方式創(chuàng)建File類

2.增刪改查

//當且僅當具有該名稱的文件尚不存在時,原子地創(chuàng)建一個由該抽象路徑名命名的新的空文件。 boolean createNewFile()//刪除由此抽象路徑名表示的文件或目錄。 boolean delete()//測試此抽象路徑名表示的文件或目錄是否存在。 boolean exists()//測試此抽象路徑名表示的文件是否為目錄。 boolean isDirectory()//測試此抽象路徑名表示的文件是否為普通文件。不是目錄,并且另外滿足其他依賴于系統的條件 boolean isFile()//創(chuàng)建由此抽象路徑名命名的目錄。 boolean mkdir()//重命名由此抽象路徑名表示的文件。 boolean renameTo(File dest)//返回一個字符串數組,命名由此抽象路徑名表示的目錄中的文件和目錄。 String[] list() //返回一個字符串數組,命名由此抽象路徑名表示的目錄中滿足指定過濾器的文件和目錄。 String[] list(FilenameFilter filter) //返回一個抽象路徑名數組,表示由該抽象路徑名表示的目錄中的文件。 File[] listFiles() //返回一個抽象路徑名數組,表示由此抽象路徑名表示的滿足指定過濾器的目錄中的文件和目錄。 File[] listFiles(FileFilter filter) //返回一個抽象路徑名數組,表示由此抽象路徑名表示的滿足指定過濾器的目錄中的文件和目錄。 File[] listFiles(FilenameFilter filter)

此外還有很多常用的方法,例如獲取絕對路徑之類的,api中很詳細,不再列出。

IO流

對于文件的讀寫,我一般習慣用這幾個FileInputStream,FileOutputStream,FileReader,FileWriter四種流.
當然,用其他的流也是一樣的
注意,所有流用完之后要記得close()

讀文件

首先是讀文件

FileInputStream

FileInputStream從文件系統中的文件獲取輸入字節(jié)。 什么文件可用取決于主機環(huán)境。
FileInputStream用于讀取諸如圖像數據的原始字節(jié)流。 要閱讀字符串,請考慮使用FileReader 。

構造方法

//通過打開與實際文件的連接創(chuàng)建一個 FileInputStream ,該文件由文件系統中的 File對象 file命名。 FileInputStream(File file) //創(chuàng)建 FileInputStream通過使用文件描述符 fdObj ,其表示在文件系統中的現有連接到一個實際的文件。 FileInputStream(FileDescriptor fdObj) //通過打開與實際文件的連接來創(chuàng)建一個 FileInputStream ,該文件由文件系統中的路徑名 name命名。 FileInputStream(String name)

常用方法

//關閉此文件輸入流并釋放與流相關聯的任何系統資源。 void close()//從該輸入流讀取一個字節(jié)的數據。 int read() //從該輸入流讀取最多 b.length個字節(jié)的數據為字節(jié)數組。 int read(byte[] b) //從該輸入流讀取最多 len字節(jié)的數據為字節(jié)數組。 int read(byte[] b, int off, int len)

實操代碼

static final int MAX = 1024*1024; int len = 0 ; byte[] buff = new byte[MAX]; StringBuffer buffer = new StringBuffer(); String text = null;String path = "F:\Desktop\test.txt"; FileInputStream input = null ;try {input = new FileInputStream(path); } catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace(); }//讀取txt文件 try {while(( (len = input.read(buff) )!= -1 )){buffer.append(new String(buff,0,len,"utf-8"));} } catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace(); }text = buffer.toString();System.out.println("text :");System.out.println(text+"\n"); try {input.close(); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace(); }

FileReader

閱讀字符文件的便利課。
該類的構造函數假定默認字符編碼和默認字節(jié)緩沖區(qū)大小是適當的。 要自己指定這些值,請在FileInputStream上構造一個InputStreamReader。
FileReader是用于讀取字符流。 要讀取原始字節(jié)流,請考慮使用FileInputStream 。

構造方法

//創(chuàng)建一個新的 FileReader ,給出 File讀取 FileReader(File file) //創(chuàng)建一個新的 FileReader ,給定 FileDescriptor讀取。 FileReader(FileDescriptor fd) //創(chuàng)建一個新的 FileReader ,給定要讀取的文件的名稱。 FileReader(String fileName)

常用方法

public class FileReader extends InputStreamReader

Methods inherited from class java.io.InputStreamReader
因為是繼承了InputStreamReader類,方法都類似

寫文件

FileOutputStream

文件輸出流是用于將數據寫入到輸出流File或一個FileDescriptor 。
文件是否可用或可能被創(chuàng)建取決于底層平臺。 特別是某些平臺允許一次只能打開一個文件來寫入一個FileOutputStream (或其他文件寫入對象)。 在這種情況下,如果所涉及的文件已經打開,則此類中的構造函數將失敗。
FileOutputStream用于寫入諸如圖像數據的原始字節(jié)流。 對于寫入字符流,請考慮使用FileWriter

構造方法

//創(chuàng)建文件輸出流以寫入由指定的 File對象表示的文件。 FileOutputStream(File file) //創(chuàng)建文件輸出流以寫入由指定的 File對象表示的文件。如果第二個參數是true ,則字節(jié)將寫入文件的末尾而不是開頭 FileOutputStream(File file, boolean append) //創(chuàng)建文件輸出流以寫入指定的文件描述符,表示與文件系統中實際文件的現有連接。 FileOutputStream(FileDescriptor fdObj) //創(chuàng)建文件輸出流以指定的名稱寫入文件。 FileOutputStream(String name) //創(chuàng)建文件輸出流以指定的名稱寫入文件。如果第二個參數是true ,則字節(jié)將寫入文件的末尾而不是開頭。 FileOutputStream(String name, boolean append)

常用方法

//關閉此文件輸入流并釋放與流相關聯的任何系統資源。 void close()//將 b.length個字節(jié)從指定的字節(jié)數組寫入此文件輸出流。 void write(byte[] b) 將 len字節(jié)從位于偏移量 off的指定字節(jié)數組寫入此文件輸出流。 void write(byte[] b, int off, int len) 將指定的字節(jié)寫入此文件輸出流。 void write(int b)

實操代碼

FileOutputStream output = null ; String path = "F:\Desktop\test.txt"; String text = "123"; try {output = new FileOutputStream(path); } catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace(); }try {output.write(text.getBytes()); } catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace(); } try {output.close(); } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace(); }

FilterWriter

方便課寫字符文件。 該類的構造函數假定默認字符編碼和默認字節(jié)緩沖區(qū)大小是可以接受的。 要自己指定這些值,請在FileOutputStream上構造一個OutputStreamWriter。
文件是否可用或可能被創(chuàng)建取決于底層平臺。 特別是某些平臺允許一次只能打開一個文件來寫入一個FileWriter (或其他文件寫入對象)。 在這種情況下,如果所涉及的文件已經打開,則此類中的構造函數將失敗。

FileWriter是用于寫入字符流。 要編寫原始字節(jié)流,請考慮使用FileOutputStream 。

構造方法

//給一個File對象構造一個FileWriter對象。 FileWriter(File file) //給一個File對象構造一個FileWriter對象。 FileWriter(File file, boolean append) //構造與文件描述符關聯的FileWriter對象。 FileWriter(FileDescriptor fd) //構造一個給定文件名的FileWriter對象。 FileWriter(String fileName) //構造一個FileWriter對象,給出一個帶有布爾值的文件名,表示是否附加寫入的數據。 FileWriter(String fileName, boolean append)

常用方法

public class FileWriter extends OutputStreamWriter

Methods inherited from class java.io.OutputStreamWriter
因為是繼承了OutputStreamWriter類,方法都類似

源代碼

我的一個demo程序:
監(jiān)聽一個目錄下的所有txt文件,讀取每一個文件的內容,然后再將其復制到另外一個目錄下。

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;public class ListenFile {private static final int MAX = 1024*1024;private String listenPath = null;private String savePath = null;private String charCode = null;File file = null;File saveFile = null;byte[] buff = new byte[MAX];int len = 0 ;String[] names = null;public ListenFile(String listenPath,String savePath,String charCode){this.listenPath = listenPath;this.savePath = savePath;this.charCode = charCode;file = new File(listenPath);saveFile = new File(savePath);if(!saveFile.exists()){saveFile.mkdir();}}public boolean judgeFile(){if(!file.exists()){System.out.println("Error,listenPath not exists");return false;}if(file.isFile()){System.out.println("Error,listenPath is a file");return false;}names = file.list((dir,name)->name.endsWith(".txt"));if((names ==null) || (names.length == 0)){System.out.println("Error,not exists TXT");return false;}return true;}public boolean readText(){for(String name : names){String path = listenPath + "/" + name;len = 0 ;StringBuffer buffer = new StringBuffer();String text = null; FileInputStream input = null ;FileOutputStream output = null ;try {input = new FileInputStream(path);} catch (FileNotFoundException e) {// TODO Auto-generated catch block//e.printStackTrace();System.out.println("Error, "+path+" not exists");}//讀取txt文件try {while(( (len = input.read(buff) )!= -1 )){buffer.append(new String(buff,0,len,charCode));}} catch (IOException e1) {// TODO Auto-generated catch block//e1.printStackTrace(); System.out.println("Error, "+path+" read fail");}//獲取txt文件中的內容text = buffer.toString();System.out.println("text :");System.out.println(text+"\n");//復制文件到目錄try {output = new FileOutputStream(savePath +"/"+name);} catch (FileNotFoundException e1) {// TODO Auto-generated catch block//e1.printStackTrace();System.out.println("Error, "+savePath +"/"+ name+" not exists");}try {output.write(text.getBytes());} catch (IOException e1) {// TODO Auto-generated catch block//e1.printStackTrace();System.out.println("Error, "+savePath + name+" copy fail");}try {input.close();output.close();} catch (IOException e) {// TODO Auto-generated catch block//e.printStackTrace();System.out.println("Error,stream close fail");}//刪除文件if(new File(path).delete()){System.out.println(path+" delete!");}else {System.out.println(name+" not delete!");}//1s處理一個文件try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return true; }}

總結

以上是生活随笔為你收集整理的Java学习之文件操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。