什么是文件?
文件可認(rèn)為是相關(guān)記錄或放在一起的數(shù)據(jù)的集合
文件一般存儲(chǔ)在哪里?
JAVA程序如何訪問(wèn)文件屬性?
java.io.File 類
File類訪問(wèn)文件屬性
JAVA中的文件及目錄處理類
在Java中提供了操作文件及目錄(即我們所說(shuō)的文件夾)類File。有以下幾點(diǎn)注意事項(xiàng):
(1)不論是文件還是目錄都使用File類操作;
(2)File類只提供操作文件及目錄的方法,并不能訪問(wèn)文件的內(nèi)容,所以他描述的是文件本身的屬性;
(3)如果要訪問(wèn)文件本身,用到了我們下面要學(xué)習(xí)的IO流.
一:構(gòu)造方法
File 文件名/目錄名 = new File("文字路徑字符串");
在Java中提供了幾種創(chuàng)建文件及目錄的構(gòu)造方法,但大體上都是用參數(shù)中的文字路徑字符串來(lái)創(chuàng)建。
二:一般方法
(1)文件檢測(cè)相關(guān)方法
boolean isDirectory():判斷File對(duì)象是不是目錄
boolean isFile():判斷File對(duì)象是不是文件
boolean exists():判斷File對(duì)象對(duì)應(yīng)的文件或目錄是不是存在
(2)文件操作的相關(guān)方法
boolean createNewFile():路徑名指定的文件不存在時(shí),創(chuàng)建一個(gè)新的空文件
boolean delete():刪除File對(duì)象對(duì)應(yīng)的文件或目錄
(3)目錄操作的相關(guān)方法
boolean mkdir():?jiǎn)螌觿?chuàng)建空文件夾
boolean mkdirs():多層創(chuàng)建文件夾
File[] listFiles():返回File對(duì)象表示的路徑下的所有文件對(duì)象數(shù)組
(4)訪問(wèn)文件相關(guān)方法
String getName():獲得文件或目錄的名字
String getAbsolutePath():獲得文件目錄的絕對(duì)路徑
String getParent():獲得對(duì)象對(duì)應(yīng)的目錄的父級(jí)目錄
long lastModified():獲得文件或目錄的最后修改時(shí)間
long length() :獲得文件內(nèi)容的長(zhǎng)度
目錄的創(chuàng)建
public class MyFile {
public static void main(String[] args) {
//創(chuàng)建一個(gè)目錄
File file1 = new File("d:\\test");
//判斷對(duì)象是不是目錄
System.out.println("是目錄嗎?"+file1.isDirectory());
//判斷對(duì)象是不是文件
System.out.println("是文件嗎?"+file1.isFile());
//獲得目錄名
System.out.println("名稱:"+file1.getName());
//獲得相對(duì)路徑
System.out.println("相對(duì)路徑:"+file1.getPath());
//獲得絕對(duì)路徑
System.out.println("絕對(duì)路徑:"+file1.getAbsolutePath());
//最后修改時(shí)間
System.out.println("修改時(shí)間:"+file1.lastModified());
//文件大小
System.out.println("文件大小:"+file1.length());
}
}
程序首次運(yùn)行結(jié)果:
是目錄嗎?false
是文件嗎?false
名稱:test
相對(duì)路徑:d:\test
絕對(duì)路徑:d:\test
修改時(shí)間:0
文件大?。?
file1對(duì)象是目錄啊,怎么在判斷“是不是目錄”時(shí)輸出了false呢?這是因?yàn)橹皇莿?chuàng)建了代表他是目錄的對(duì)象,還沒(méi)有真正的創(chuàng)建,這時(shí)候要用到mkdirs()方法,如下:
public class MyFile {
public static void main(String[] args) {
//創(chuàng)建一個(gè)目錄
File file1 = new File("d:\\test\\test");
file1.mkdirs();//創(chuàng)建了多級(jí)目錄
//判斷對(duì)象是不是目錄
System.out.println("是目錄嗎?"+file1.isDirectory());
}
}
文件的創(chuàng)建
public class MyFile {
public static void main(String[] args) {
//創(chuàng)建一個(gè)文件
File file1 = new File("d:\\a.txt");
//判斷對(duì)象是不是文件
System.out.println("是文件嗎?"+file1.isFile());
}
}
首次運(yùn)行結(jié)果:
是文件嗎?false
同樣會(huì)發(fā)現(xiàn)類似于上面的問(wèn)題,這是因?yàn)橹皇谴砹艘粋€(gè)文件對(duì)象,并沒(méi)有真正的創(chuàng)建,要用到createNewFile()方法,如下
public class MyFile {
public static void main(String[] args) {
//創(chuàng)建一個(gè)文件對(duì)象
File file1 = new File("d:\\a.txt");
try {
file1.createNewFile();//創(chuàng)建真正的文件
} catch (IOException e) {
e.printStackTrace();
}
//判斷對(duì)象是不是文件
System.out.println("是文件嗎?"+file1.isFile());
}
}
文件夾與文件的創(chuàng)建目錄
文件時(shí)存放在文件夾下的,所以應(yīng)該先創(chuàng)建文件夾,后創(chuàng)建文件,如下:
public class MyFile {
public static void main(String[] args) {
//代表一個(gè)文件夾對(duì)象,單層的創(chuàng)建
File f3 = new File("d:/test");
File f4 = new File("d:/test/a.txt");
f3.mkdir();//先創(chuàng)建文件夾,才能在文件夾下創(chuàng)建文件
try {
f4.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//代表一個(gè)文件夾對(duì)象,多層的創(chuàng)建
File f5= new File("d:/test/test/test");
File f6 = new File("d:/test/test/test/a.txt");
f5.mkdirs();//多層創(chuàng)建
try {
f6.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
運(yùn)行結(jié)果為,在D磁盤的test文件夾下有一個(gè)a.txt,在D磁盤的test/test/test下有一個(gè)a.txt文件。
編程:判斷是不是有這個(gè)文件,若有則刪除,沒(méi)有則創(chuàng)建
public class TestFileCreatAndDele {
public static void main(String[] args) {
File f1 = new File("d:/a.txt");
if(f1.exists()){//文件在嗎
f1.delete();//在就刪除
}else{//不在
try {
f1.createNewFile();//就重新創(chuàng)建
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件的逐層讀取
File的listFiles()只能列出當(dāng)前文件夾下的文件及目錄,那么其子目錄下的文件及目錄該如何獲取呢?解決的辦法有很多,在這運(yùn)用遞歸解決.
//逐層獲取文件及目錄
public class TestFindFile {
public static void openAll(File f) {// 遞歸的實(shí)現(xiàn)
File[] arr = f.listFiles();// 先列出當(dāng)前文件夾下的文件及目錄
for (File ff : arr) {
if (ff.isDirectory()) {// 列出的東西是目錄嗎
System.out.println(ff.getName());
openAll(ff);// 是就繼續(xù)獲得子文件夾,執(zhí)行操作
} else {
// 不是就把文件名輸出
System.out.println(ff.getName());
}
}
}
public static void main(String[] args) {
File file = new File("d:/test");// 創(chuàng)建目錄對(duì)象
openAll(file);// 打開(kāi)目錄下的所有文件及文件夾
}
}
流
如何讀寫文件?
通過(guò)流來(lái)讀寫文件
流是指一連串流動(dòng)的字符,是以先進(jìn)先出方式發(fā)送信息的通道
輸入/輸出流與數(shù)據(jù)源
Java流的分類
文本文件的讀寫
- 用FileInputStream和FileOutputStream讀寫文本文件
- 用BufferedReader和BufferedWriter讀寫文本文件
二進(jìn)制文件的讀寫
- 使用DataInputStream和DataOutputStream讀寫二進(jìn)制文件
使用FileInputStream 讀文本文件
InputStream類常用方法
int read( )
int read(byte[] b)
int read(byte[] b,int off,int len)
void close( )
子類FileInputStream常用的構(gòu)造方法
FileInputStream(File file)
FileInputStream(String name)
一個(gè)一個(gè)字節(jié)的讀
public static void main(String[] args) throws IOException {
// write your code here
File file = new File("d:/我的青春誰(shuí)做主.txt");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[100];//保存從磁盤讀到的字節(jié)
int index = 0;
int content = fileInputStream.read();//讀文件中的一個(gè)字節(jié)
while (content != -1)//文件中還有內(nèi)容,沒(méi)有讀完
{
buffer[index] = (byte)content;
index++;
//讀文件中的下一個(gè)字節(jié)
content = fileInputStream.read();
}
//此時(shí)buffer數(shù)組中讀到了文件的所有字節(jié)
String string = new String(buffer,0, index);
System.out.println(string);
}
一批一批的讀
public static void main(String[] args) throws IOException {
// write your code here
File file = new File("d:/我的青春誰(shuí)做主.txt");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[SIZE];//保存從磁盤讀到的字節(jié)
int len = fileInputStream.read(buffer);//第一次讀文件中的100個(gè)字節(jié)
while (len != -1)
{
String string = new String(buffer,0, len);
System.out.println(string);
//讀下一批字節(jié)
len = fileInputStream.read(buffer);
}
}
使用FileOutputStream 寫文本文件
public class FileOutputStreamTest {
public static void main(String[] args) {
FileOutputStream fos=null;
try {
String str ="好好學(xué)習(xí)Java";
byte[] words = str.getBytes();
fos = new FileOutputStream("D:\\myDoc\\hello.txt");
fos.write(words, 0, words.length);
System.out.println("hello文件已更新!");
}catch (IOException obj) {
System.out.println("創(chuàng)建文件時(shí)出錯(cuò)!");
}finally{
try{
if(fos!=null)
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStream類常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close( )
子類FileOutputStream常用的構(gòu)造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)
1、前兩種構(gòu)造方法在向文件寫數(shù)據(jù)時(shí)將覆蓋文件中原有的內(nèi)容
2、創(chuàng)建FileOutputStream實(shí)例時(shí),如果相應(yīng)的文件并不存在,則會(huì)自動(dòng)創(chuàng)建一個(gè)空的文件
復(fù)制文件內(nèi)容
文件“我的青春誰(shuí)做主.txt”位于D盤根目錄下,要求將此文件的內(nèi)容復(fù)制到
C:\myFile\my Prime.txt中
實(shí)現(xiàn)思路
- 創(chuàng)建文件“D:\我的青春誰(shuí)做主.txt”并自行輸入內(nèi)容
- 創(chuàng)建C:\myFile的目錄。
- 創(chuàng)建輸入流FileInputStream對(duì)象,負(fù)責(zé)對(duì)D:\我的青春誰(shuí)做主.txt文件的讀取。
- 創(chuàng)建輸出流FileOutputStream對(duì)象,負(fù)責(zé)將文件內(nèi)容寫入到C:\myFile\my Prime.txt中。
- 創(chuàng)建中轉(zhuǎn)站數(shù)組words,存放每次讀取的內(nèi)容。
- 通過(guò)循環(huán)實(shí)現(xiàn)文件讀寫。
- 關(guān)閉輸入流、輸出流
public static void main(String[] args) throws IOException {
//創(chuàng)建E:\myFile的目錄。
File folder = new File("E:\\myFile");
if (!folder.exists())//判斷目錄是否存在
{
folder.mkdirs();//如果不存在,創(chuàng)建該目錄
}
//創(chuàng)建輸入流
File fileInput = new File("d:/b.rar");
FileInputStream fileInputStream = new FileInputStream(fileInput);
//創(chuàng)建輸出流
FileOutputStream fileOutputStream = new FileOutputStream("E:\\myFile\\c.rar");
//創(chuàng)建中轉(zhuǎn)站數(shù)組buffer,存放每次讀取的內(nèi)容
byte[] buffer = new byte[1000];
//從fileInputStream(d:/我的青春誰(shuí)做主.txt)中讀100個(gè)字節(jié)到buffer中
int length = fileInputStream.read(buffer);
int count = 0;
while (length != -1) //這次讀到了至少一個(gè)字節(jié)
{
System.out.println(length);
//將buffer中內(nèi)容寫入到輸出流(E:\myFile\myPrime.txt)
fileOutputStream.write(buffer,0,length);
//繼續(xù)從輸入流中讀取下一批字節(jié)
length = fileInputStream.read(buffer);
count++;
}
System.out.println(count);
fileInputStream.close();
fileOutputStream.close();
}
使用字符流讀寫文件
使用FileReader讀取文件
public static void main(String[] args) throws IOException {
//
FileReader fileReader = new FileReader("D:/我的青春誰(shuí)做主.txt");
char[] array = new char[100];
int length = fileReader.read(array);
StringBuilder sb = new StringBuilder();
while (length != -1)
{
sb.append(array);
length = fileReader.read(array);
}
System.out.println(sb.toString());
fileReader.close();
}
BufferedReader類
如何提高字符流讀取文本文件的效率?
使用FileReader類與BufferedReader類
BufferedReader類是Reader類的子類
BufferedReader類帶有緩沖區(qū)
按行讀取內(nèi)容的readLine()方法
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("D:/我的青春誰(shuí)做主.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String strContent = bufferedReader.readLine();
StringBuilder sb = new StringBuilder();
while (strContent != null)
{
sb.append(strContent);
sb.append("\n");
sb.append("\r");
strContent = bufferedReader.readLine();
}
System.out.println(sb.toString());
fileReader.close();
bufferedReader.close();
}
使用FileWriter寫文件
public class WriterFiletTest {
/**
* @param args
*/
public static void main(String[] args) {
Writer fw=null;
try {
//創(chuàng)建一個(gè)FileWriter對(duì)象
fw=new FileWriter("D:\\myDoc\\簡(jiǎn)介.txt");
//寫入信息
fw.write("我熱愛(ài)我的團(tuán)隊(duì)!");
fw.flush(); //刷新緩沖區(qū)
}catch(IOException e){
System.out.println("文件不存在!");
}finally{
try {
if(fw!=null)
fw.close(); //關(guān)閉流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如何提高字符流寫文本文件的效率?
使用FileWriter類與BufferedWriter類
BufferedWriter類是Writer類的子類
BufferedWriter類帶有緩沖區(qū)
public class BufferedWriterTest {
public static void main(String[] args) {
FileWriter fw=null;
BufferedWriter bw=null;
FileReader fr=null;
BufferedReader br=null;
try {
//創(chuàng)建一個(gè)FileWriter 對(duì)象
fw=new FileWriter("D:\\myDoc\\hello.txt");
//創(chuàng)建一個(gè)BufferedWriter 對(duì)象
bw=new BufferedWriter(fw);
bw.write("大家好!");
bw.write("我正在學(xué)習(xí)BufferedWriter。");
bw.newLine();
bw.write("請(qǐng)多多指教!");
bw.newLine();
bw.flush();
//讀取文件內(nèi)容
fr=new FileReader("D:\\myDoc\\hello.txt");
br=new BufferedReader(fr);
String line=br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
fr.close();
}catch(IOException e){
System.out.println("文件不存在!");
}finally{
try{
if(fw!=null)
fw.close();
if(br!=null)
br.close();
if(fr!=null)
fr.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
作者:豆約翰
鏈接:http://www.itdecent.cn/p/5759570f9d8b
來(lái)源:簡(jiǎn)書
簡(jiǎn)書著作權(quán)歸作者所有,任何形式的轉(zhuǎn)載都請(qǐng)聯(lián)系作者獲得授權(quán)并注明出處。