天天看點

Java基礎——IO流與檔案操作(上)

25、IO流(上)

概述

IO流(Input Output)流

IO流用來裝置間的資料傳輸

Java對資料的操作通過流的方式

Java操作流的對象都在IO包中

流按操作資料分為兩種:

位元組流和字元流

流按流向分為:

輸入流和輸出流

IO流常用基類:

位元組流的抽象基類:InputStream OutputStream

字元流的抽象基類:Reader Writer

既然IO流是用于操作資料的,那麼資料最常見的展現形式是,以操作檔案為主來示範

需求:在硬碟上,建立一個檔案,并寫入一些文字資料

找到一個專門用于操作檔案的Writer子類對象叫做FileWriter,字尾名是父類名。 字首名是該流對象的功能。

步驟:

1、建立一個FileWriter對象,該對象一旦初始化就必須要明确操作的檔案,而且該檔案會被建立在指定目錄下。如果該目錄已有同名檔案,将被覆寫,其實該步就是要明确資料存放目的地

2、調用write方法,将字元串寫入到流中

3、重新整理流對象中緩沖區的資料,将資料刷到目的地中

4、Close:關閉流資源,但是關閉之前會重新整理一次,内部中的緩沖資料

5、Close和flush的差別:flush重新整理後,流可以繼續使用,close重新整理後,流将關閉

package days11;

import java.io.*;

public class FileWriter1 

{

public static void main(String[]args)throws IOException

{

FileWriter fw=new FileWriter("C:\\demo.txt");

fw.write("abcde");

fw.flush();

fw.write("你好IO!!!");

fw.flush();

fw.close();

}

}

package days11;

import java.io.FileWriter;

import java.io.IOException;

import java.io.OutputStreamWriter;

public class IOEx 

{

public static void main(String[]args) throws IOException

{FileWriter fw=null;

   try

   {

 fw=new FileWriter("C:\\demo.txt");

    fw.write("abcdefg");

   }

   catch(IOException e)

   {

   System.out.println(e.toString());

   }

   finally

   {

 fw.close();

   }

}

}

檔案的續寫

package days11;

import java.io.*;

public class FileWriter2 

{

public static void main(String[]args) throws IOException

{

FileWriter fw=new FileWriter("C:\\demo.txt",true);

fw.write("  haha");

fw.write("\r\nhaha");

fw.close();

}

}

FileWriter fw=new FileWriter("C:\\demo.txt",true);

傳遞一個true參數,代表不覆寫已有檔案,并在已有檔案的結尾處,進行資料續寫

檔案文本讀取方式

package days11;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class Filereader1 

{

public static void main(String[]args) throws IOException

{

FileReader fr=new FileReader("C:\\demo.txt");

int ch=fr.read();

System.out.println("ch="+ch);

while(true)

{

int ch1=fr.read();

if(ch1==-1)

{

break;

}

System.out.print((char)ch1);

}

}

}

建立一個文本讀取流對象,和指定名稱的檔案相關聯,要保證該檔案是否已經存在,如果不存在,會發生文本未找到異常

Read():一次讀一個字元,而且會自動往下讀。

package days11;

import java.io.*;

public class FileReader2 

{

  public static void main(String[]args)throws IOException

  {

  FileReader fr=new FileReader("C:\\demo.txt");

  char[]buf=new char[3];

  int num=fr.read(buf);

  System.out.println("num="+num+"..."+new String(buf));

  while((num=fr.read(buf))!=-1)

{

System.out.print(new String(buf,0,num));

}

  fr.close();

  }

}

通過字元數組進行讀取

拷貝文本檔案

将C槽的一個文本檔案複制到D盤

複制的原理:将C槽的檔案資料存儲到D盤的一個檔案中

步驟:1、在D盤建立一個檔案,用于存儲C槽檔案的資料

      2、定義讀取流和C槽關聯

      3、通過不斷讀寫完成資料存儲

      4、關閉資源

package days11;

import java.io.*;

public class RW 

{

public static void main(String[]args) throws IOException

{

copy1();

copy2();

}

public static void copy1() throws IOException

{

FileReader fr=new FileReader("C:\\demo.txt");

FileWriter fw=new FileWriter("D:\\demo.txt");

int ch=0;

while((ch=fr.read())!=-1)

{

fw.write(ch);

}

fw.close();

fr.close();

}

public static void copy2()throws IOException

{

FileWriter fw=null;

FileReader fr=null;

    try

    {

     fw=new FileWriter("D:\\demo2.txt");

     fr=new FileReader("C:\\demo.txt");

     int len=0;

     char[]buf=new char[1024];

     while((len=fr.read(buf))!=-1)

     {

     fw.write(buf,0,len);

     }

    }

    catch(IOException e)

    {

     throw new RuntimeException("讀寫失敗");

    }

    finally

    {

     fr.close();

     fw.close();

    }

}

}

BufferedWriter

字元流緩沖區

緩沖區的出現是為了提高流的操作效率

緩沖區的出現提高了對資料的讀寫率,是以在建立緩沖區之前,要先有流對象

對應類

BufferedWriter

BufferedReader

緩沖區要結合流才可以使用

步驟:

1、建立一個流對象

2、隻要将需要提高效率的流對象作為參數傳遞給緩沖區的構造函數即可

3、隻要用到緩沖區,就要記得重新整理

4、關閉緩沖區就是關閉緩沖區的流對象

package days13;

import java.io.*;

public class BufferedWriter1 

{

   public static void main(String[]args) throws IOException

   {

   FileWriter fw=new FileWriter("C:\\buf.txt");

   BufferedWriter bufw=new BufferedWriter(fw);

   bufw.write("abc\r\nde");

   bufw.write("gogogo");

   bufw.newLine();

   for(int x=1;x<5;x++)

   {

   bufw.write("abcd"+x);

   bufw.newLine();

   bufw.flush();

   }

   }

}

BufferedReader

步驟:

1、建立一個讀取流對象和檔案相關聯

2、為了提高效率,加入緩沖技術,将字元讀取流對象作為參數,傳遞給緩沖對象的構造函數

3、該緩沖區提供了一個一次讀一行的方法,readLine,友善于對文本資料的擷取,當讀到null時,表示讀到檔案末尾 

package days13;

import java.io.*;

public class BufferedReader1 

{

    public static void main(String[]args) throws IOException

    {

     FileReader fr=new FileReader("C:\\buf.txt");

     BufferedReader bufr=new BufferedReader(fr);

     String line=null;

     while((line=bufr.readLine())!=null)

     {

     System.out.println(line);

     }

     String s=bufr.readLine();

     System.out.println("s="+s);

     bufr.close();

    }

}

通過緩沖區複制文本檔案

package days11;

import java.io.*;

public class RW 

{

public static void main(String[]args) throws IOException

{

copy1();

copy2();

}

public static void copy1() throws IOException

{

FileReader fr=new FileReader("C:\\paixu.java");

FileWriter fw=new FileWriter("D:\\demo.txt");

int ch=0;

while((ch=fr.read())!=-1)

{

fw.write(ch);

}

fw.close();

fr.close();

}

public static void copy2()throws IOException

{

FileWriter fw=null;

FileReader fr=null;

    try

    {

     fw=new FileWriter("D:\\demo2.txt");

     fr=new FileReader("C:\\demo.txt");

     int len=0;

     char[]buf=new char[1024];

     while((len=fr.read(buf))!=-1)

     {

     fw.write(buf,0,len);

     }

    }

    catch(IOException e)

    {

     throw new RuntimeException("讀寫失敗");

    }

    finally

    {

     fr.close();

     fw.close();

    }

}

}

readLine方法傳回時隻傳回回車前的資料内容,并不傳回回車符

readLine方法原理:無論是讀一行,還是讀取多個字元,其實最終都是在硬碟上一個一個讀取,是以最終使用的還是read方法一次讀一個

MyBufferedReader

明白了BufferedReader類中的特有方法readLine原理後,可以自定義一個類中包含一個功能和readLine一緻的方法,來模拟一下BufferedReader

package days13;

import java.io.*;

public class Mybuf 

{

    public static void main(String[]args) throws IOException

    {

     FileReader fr=new FileReader("C:\\buf.txt");

     Mybuf buf=new Mybuf(fr);

     String line=null;

     while((line=buf.myreadLine())!=null)

     {

     System.out.println(line);

     }

     fr.close();

    }

    private FileReader r;

     Mybuf(FileReader r)

    {

     this.r=r;

    }

     public String myreadLine()throws IOException

     {

     StringBuilder sb=new StringBuilder();

     int ch=0;

     while((ch=r.read())!=-1)

     {

     if(ch=='\r')

     continue;

     if(ch=='\n')

     return sb.toString();

     else

     sb.append((char)ch);

     }

     if(sb.length()!=0)

        return sb.toString();

     return null;

     }

}

31、裝飾設計模式

裝飾設計模式:

當想要對已有的對象進行功能增強時,可以定義類,将已有對象傳入,基于已有的對象,并提供加強的功能,那麼自定義的類成為裝飾類。裝飾類通常通過構造方法接收被裝飾的對象,并基于被裝飾的對象的功能,提供更強的功能。

package days13;

public class Zhuangshi 

{

   public static void main(String[]args)

   {

   Person p=new Person();

   superPerson p1=new superPerson(p);

   p1.superchifan();

   }

}

class Person

{

public void chifan()

{

System.out.println("吃飯");

}

}

class superPerson

{

private Person p;

superPerson(Person p)

{

this.p=p;

}

public void superchifan()

{

p.chifan();

System.out.println("喝湯");

}

}

裝飾和繼承的差別

裝飾模式比繼承要靈活,避免了繼承體系的臃腫,而且降低了類與類之間的關系,裝飾類因為增強它已有的對象,具備的功能和已有的是相同的,隻不過提供了更強的功能,是以裝飾類和被裝飾類通常都屬于一個體系中

32、IO流(下)

LineNumberReader

package days13;

import java.io.*;

public class Linenum 

{

   public static void main(String[]args)throws IOException

   {

   FileReader fr=new FileReader("C:\\paixu.java");

   LineNumberReader lnr=new LineNumberReader(fr);

   String line=null;

   while((line=lnr.readLine())!=null)

   {

   System.out.println(lnr.getLineNumber()+line);

   }

   }

}

MyLineNumberReader

package days13;

import java.io.*;

class MyBufferedReader extends Reader

{

private Reader r;

MyBufferedReader(Reader r)

{

this.r = r;

}

//可以一次讀一行資料的方法。

public String myReadLine()throws IOException

{

//定義一個臨時容器。原BufferReader封裝的是字元數組。

//為了示範友善。定義一個StringBuilder容器。因為最終還是要将資料變成字元串。

StringBuilder sb = new StringBuilder();

int ch = 0;

while((ch=r.read())!=-1)

{

if(ch=='\r')

continue;

if(ch=='\n')

return sb.toString();

else

sb.append((char)ch);

}

if(sb.length()!=0)

return sb.toString();

return null;

}

public int read(char[] cbuf, int off, int len) throws IOException

{

return r.read(cbuf,off,len) ;

}

public void close()throws IOException

{

r.close();

}

public void myClose()throws IOException

{

r.close();

}

}

class MyLineNumberReader extends MyBufferedReader

{

private int lineNumber;

MyLineNumberReader(Reader r)

{

super(r);

}

public String myReadLine()throws IOException

{

lineNumber++;

return super.myReadLine();

}

public void setLineNumber(int lineNumber)

{

this.lineNumber = lineNumber;

}

public int getLineNumber()

{

return lineNumber;

}

}

class  MyLineNumberReaderDemo

{

public static void main(String[] args) throws IOException

{

FileReader fr = new FileReader("copyTextByBuf.java");

MyLineNumberReader mylnr = new MyLineNumberReader(fr);

String line = null;

mylnr.setLineNumber(100);

while((line=mylnr.myReadLine())!=null)

{

System.out.println(mylnr.getLineNumber()+"::"+line);

}

mylnr.myClose();

}

}

位元組流File讀寫操作

需求:想要操作圖檔資料,這時要用到位元組流

1、用位元組流讀取流對象和圖檔關聯

2、用位元組寫入流對象,建立一個圖檔檔案,用于存儲擷取到的圖檔資料

3、通過循環讀寫,完成資料存儲

4、關閉資源

package days13;

import java.io.*;

public class Copypic 

{

 public static void main(String[]args) throws IOException

 {

 FileInputStream fis=null;

 FileOutputStream fos=null;

 try

 {

 fos=new FileOutputStream("C:\\2.jpg");

 fis=new FileInputStream("C:\\1.jpg");

 byte[] by=new byte[1024];

 int len=0;

 while((len=fis.read(by))!=-1)

 {

 fos.write(by,0,len);

 }

 }

 catch(IOException e)

 {

 throw new RuntimeException("失敗");

 }

 finally

 {

 fis.close();

 fos.close();

 }

 }

}

位元組流的緩沖區

package days14;

import java.io.*;

public class MP 

{

    public static void main(String[]args) throws IOException

    {

     long start=System.currentTimeMillis();

     copy();

     long end=System.currentTimeMillis();

     System.out.println(end-start+"毫秒");

    }

   public static void copy() throws IOException

   {

   BufferedInputStream bufrs=new BufferedInputStream(new FileInputStream("C:\\1.doc"));

   BufferedOutputStream bufro=new BufferedOutputStream(new FileOutputStream("C:\\2.doc"));

   byte[]by=new byte[1024];

   int ch=0;

   while((ch=bufrs.read(by))!=-1)

   {

   bufro.write(by);

   }

   bufrs.close();

   bufro.close();

   }

}

自定義位元組流緩沖區read和write的特點

import java.io.*;

class MyBufferedInputStream

{

private InputStream in;

private byte[] buf = new byte[1024*4];

private int pos = 0,count = 0;

MyBufferedInputStream(InputStream in)

{

this.in = in;

}

//一次讀一個位元組,從緩沖區(位元組數組)擷取。

public int myRead()throws IOException

{

//通過in對象讀取硬碟上資料,并存儲buf中。

if(count==0)

{

count = in.read(buf);

if(count<0)

return -1;

pos = 0;

byte b = buf[pos];

count--;

pos++;

return b&255;

}

else if(count>0)

{

byte b = buf[pos];

count--;

pos++;

return b&0xff;

}

return -1;

}

public void myClose()throws IOException

{

in.close();

}

}

讀取鍵盤錄入

System.in:對應 标準輸入裝置:鍵盤

System.out:對應标準輸出裝置,控制台

通過鍵盤導入資料,當錄入一行資料後,就将該行資料進行列印。如果錄入的資料時over,那麼停止錄入

package days14;

import java.io.*;

public class ReadIn 

{

   public static void main(String[]args) throws IOException

   {

  //read1();

   read2();

   }

   public static void read1()throws IOException

   {

   InputStream in=System.in;

   int ch=0;

   while((ch=in.read())!=-1)

   {

   System.out.println(ch);

   }

   }

   public static void read2()throws IOException

   {

   InputStream in=System.in;

   StringBuilder sb=new StringBuilder();

   while(true)

   {

   int ch=in.read();

   if(ch=='\r')

   continue;

   if(ch=='\n')

   {

   String s=sb.toString();

   System.out.println(s);

   sb.delete(0, sb.length());

   if(s.equals("over"))

   {

   break;

   }

   }

   else

   sb.append((char)ch);

   }

   }

}

讀取轉換流

通過剛才的鍵盤錄入一行資料并列印,發現其實就是讀一行資料原理,也就是readLine方法,

能不能直接使用readLine方法直接來完成鍵盤錄入一行資料的讀取呢

readLine方法是BufferedReader類中的方法,而鍵盤錄入的read方法是InputStream的方法

那麼能不能将位元組流轉成字元流再使用字元流緩沖區的readLine方法呢

package days14;

import java.io.*;

public class TranStr 

{

   public static void main(String[]args) throws IOException

   {

   BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

   BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));

   String line=null;

   while((line=bufr.readLine())!=null)

   {

   if(line.equals("over"))

   break;

   bufw.write(line);

   bufw.newLine();

   bufw.flush();

   }

   }

}

流操作規律

需求:想把鍵盤錄入的資料存儲到一個檔案中

源:鍵盤

目的:檔案

變化的部分:

BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));

BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(FileOutputStream(""1.txt))));

需求:想要将一個檔案的資料列印在控制台上

源:檔案

目的:控制台

變化的部分

BufferedReader bufr=new BufferedReader(new InputStreamReader(new FileInputStream("1.txt")));

BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out));

最痛苦的是流對象有很多,不知道該選用哪一個?

通過兩個明确來完成

1、明确源和目的

源:輸入流 

目的:輸出流

2、操作的資料是否是純文字

輸入流:InputStream    Reader    是純文字:字元流

輸出流:OutputStream   Writer    不是純文字:位元組流

當體系明确後,再明确要使用哪個具體的對象

通過對裝置進行區分:

源裝置:記憶體、硬碟、鍵盤

目的裝置:記憶體、硬碟、控制台

将一個文本檔案中的資料存儲到另一個檔案中——複制檔案

源:InputStream,Reader(因為是源是以使用讀取流)

是不是操作純文字檔案:是,這時候選擇Reader

接下來明确對象:明确裝置,硬碟,Reader體系中可以操作的檔案對象是FileReader

FileReader fr=new FileReader("a.txt");

是否需要提高效率:是,加入Reader體系中的緩沖區BufferedReader

BufferedReader bufr=new BufferedReader(fr);

目的:OutputStream Writer

是否是純文字:是,Writer

明确裝置:硬碟,一個檔案

Writer體系中可以操作的檔案對象時FileWriter

FileWriter fw=new FileWriter("b.txt");

是否需要提高效率:是

加入Writer體系中的緩沖區:BufferedWriter

BufferedWriter bufw=new BufferedWriter(fw);

将鍵盤導入資料,儲存到一個檔案中

這個需求源和目的都存在,那麼分别分析

源:InputStream、Reader

是不是純文字:是!Reader

裝置:鍵盤,對應的對象是System.in

不是選擇Reader嗎?System.in不是對應的位元組流嗎?

為了操作鍵盤的文本資料友善,轉換成字元流,按照字元串操作時最友善的,是以既然明确了Reader,那麼就将System.in轉換成Reader,用了Reader體系中的轉換流:InputStreamReader

InputStream Reader isr=new InputStreamReader(System.in)

需要提高效率嗎?

是!BufferedReader

BufferedReader bufr=new BufferedReader(isr);

目的:OutputStream Writer

是否是純文字:是!Writer

裝置:鍵盤,一個檔案使用,FileWriter

FileWriter fw=new FileWriter("c.txt");

需要提高工作效率嗎?

需要,BufferedWriter

BufferedWriter bufw=new BufferedWriter(fw);

練習代碼:

package days14;

import java.io.*;

public class Test1 

{

    public static void main(String[]args) throws IOException

    {

     //copy_1();

     //copy_2();

     copy_3();

    }

    public static void copy_1() throws IOException

    {

     BufferedWriter bufw=new BufferedWriter(new FileWriter("C:\\dy.txt"));

     BufferedReader bufr=new BufferedReader(new FileReader("C:\\pai.java"));

     String len=null;

     while((len=bufr.readLine())!=null)

     {

     bufw.write(len);

     bufw.newLine();

     bufw.flush();

     System.out.println(len);

     }

     bufr.close();

     bufw.close();

    }

    public static void copy_2() throws IOException

    {

     BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));

     BufferedWriter bufw=new BufferedWriter(new FileWriter("C:\\text.txt")); 

     String len=null;

     while((len=bufr.readLine())!=null)

     {

     bufw.write(len);

     bufw.flush();

     bufw.newLine();

     System.out.println(len);

     }

     bufw.close();

     bufr.close();

    }

    public static void copy_3()throws IOException

    {

     FileInputStream fis=new FileInputStream("C:\\1.jpg");

     FileOutputStream fos=new FileOutputStream("C:\\5.jpg");

     int len=0;

     while((len=fis.read())!=-1)

     {

     fos.write(len);

     fos.flush();

     System.out.print((char)len);

     }

     fos.close();

     fis.close();

    }

}

想要把錄入的資料按照指定的編碼表,将資料存到檔案中

目的:OutStream、Writer

是否是純文字?

是 Writer

裝置:硬碟,一個檔案,使用FileWriter

但是存儲的時候需要加入指定的編碼表,而指定的編碼表示有轉換流可以指定

是以要使用的是對象是OutputStreamWriter

是以轉換流對象要接收一個位元組輸出流 FileoutputStream

本想用FileWriter,但是它使用的是預設編碼表:GBK

OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("d.txt","UTF-8"));

需要高效嗎?需要

BufferedWriter bufw=new BufferedWriter(osw);

是以記住轉換流什麼時候使用,字元和位元組之間的橋梁,通常涉及到:字元編碼轉換流

練習代碼:

package days14;

import java.io.*;

public class Trans 

{

   public static void main(String[]args) throws IOException

   {

  //show_1();

show_2();

   }

   public static void show_1()throws IOException

   {

   BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));

   BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter((new FileOutputStream("C:\\dy.txt")),"UTF-8"));

   String line=null;

   while((line=bufr.readLine())!=null)

   {

   bufw.write(line);

   bufw.newLine();

   bufw.flush();

   }

   bufw.close();

   bufr.close();

   }

   public static void show_2()throws IOException

   {

   BufferedReader bfr=new BufferedReader(new InputStreamReader(new FileInputStream("C:\\1.jpg")));

   BufferedWriter bfw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\demo.txt"),"UTF-8"));

   String len=null;

   while((len=bfr.readLine())!=null)

   {

   bfw.write(len);

   bfw.newLine();

   bfw.flush();

   }

   bfw.close();

   bfr.close();

   }

}

改變标準輸入輸出裝置

System.setIn(new FileInputStream("PersonDemo.java"));

System.setOut(new PrintStream("zzz.txt"));

異常的日志資訊

package days14;

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.Date;

public class ExInfo 

{

   public static void main(String[]args) throws Exception 

   {

   try

   {

   int[]arr=new int[2];

   System.out.println(arr[3]);

   }

   catch(Exception e)

   {

  try

  {

    Date d = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String s = sdf.format(d);

PrintStream ps = new PrintStream("C:\\123.log");

ps.println(s);

System.setOut(ps);

  }

  catch(IOException ex)

  {

 throw new RuntimeException("日志建立失敗!!!");

  }

  e.printStackTrace(System.out);

   }

   }

}

系統資訊

package days14;

import java.io.*;

import java.util.Properties;

public class Syst 

{

   public static void main(String[]args) throws FileNotFoundException

   {

   Properties prop=System.getProperties();

   prop.list(new PrintStream("C:\\demo.txt"));

   }

}

34、File類

用來将檔案或檔案夾封裝成對象,友善對檔案或檔案夾進行修改。File對象可以作為參數傳遞給流的構造函數。

package days15;

import java.io.*;

public class File1 

{

   public static void main(String[]args)

   {

File f1 = new File("a.txt");

//

File f2 = new File("c:\\abc","b.txt");

File d = new File("c:\\abc");

File f3 = new File(d,"c.txt");

sop("f1:"+f1);

sop("f2:"+f2);

sop("f3:"+f3);

File f4 = new File("c:"+File.separator+"abc"+File.separator+"zzz"+File.separator+"a.txt");

}

public static void sop(Object obj)

{

System.out.println(obj);

}

}

File類常見方法:

1,建立。

boolean createNewFile():在指定位置建立檔案,如果該檔案已經存在,則不建立,傳回false。和輸出流不一樣,輸出流對象一建立建立檔案。而且檔案已經存在,會覆寫。

boolean mkdir():建立檔案夾。

boolean mkdirs():建立多級檔案夾。

2,删除。

boolean delete():删除失敗傳回false。如果檔案正在被使用,則删除不了傳回falsel。

void deleteOnExit();在程式退出時删除指定檔案。

3,判斷。

boolean exists() :檔案是否存在.

isFile():

isDirectory();

isHidden();

isAbsolute();

4,擷取資訊。

getName():

getPath():

getParent():

getAbsolutePath() 

long lastModified() 

long length() 

package days15;

import java.io.*;

public class File2 

{

   public static void main(String[]args) throws IOException

   {

   File f=new File("C:\\demo.txt");

   sop("creat:"+f.createNewFile());

   sop("delete:"+f.delete());

   }

   public static void sop(Object obj)

   {

  System.out.println(obj);

   }

}

判斷

package days15;

import java.io.*;

public class File3 

{

   public static void main(String[]args)

   {

   File f=new File("C:\\demo2.txt");

   sop("exists:"+f.exists());

   sop("execute:"+f.canExecute());

   File dir=new File("C:\\abcf");

   sop("mkdir:"+dir.mkdir());

   File dir2=new File("C:\\abcf\\kkk");

   sop("mkdirs:"+dir2.mkdirs());

       sop("dir:"+f.isDirectory());

   sop("file:"+f.isFile());

   sop(f.isAbsolute());

   }

   public static void sop(Object obj)

   {

   System.out.println(obj);

   }

}

記住在判斷檔案對象是否是檔案或者目的時,必須要判斷該檔案對象封裝的内容是否存在,通過exists判斷

擷取資訊

package days15;

import java.io.*;

public class File5 

{

   public static void main(String[]args)

   {

   File f=new File("C:\\demo2.txt");

   sop("path:"+f.getPath());

   sop("abspath:"+f.getAbsolutePath());

   sop("parent:"+f.getParent());

   File f1=new File("C:\\dy.txt");

   File f2=new File("C:\\fos2.txt");

   sop("rename:"+f.renameTo(f2));

   }

   public static void sop(Object obj)

   {

   System.out.println(obj);

   }

}

File對象功能——檔案清單

package days15;

import java.io.*;

public class File6 

{

    public static void main(String[]args)

    {

     File[]files=File.listRoots();

     for(File f:files)

     {

     System.out.println(f);

     }

     list();

    }

    public static void list()

    {

     File f=new File("C:\\");

     String[]names=f.list();

     for (String name:names)

     {

     System.out.println(name);

     }

    }

}

調用list方法,list對象必須是封裝了一個目錄,該目錄還必須存在

File對象功能——檔案清單2

package days15;

import java.io.*;

public class File7 

{

  public static void main(String[]args)

    {

     File f=new File("C:\\");

     String[]names=f.list();

       String []st=new String[names.length];

       int n=0;

       for(int i = 0;i<names.length;i++)

       {

        if(!names[i].endsWith(".jpg"))

        continue;

       st[n]=names[i]; 

       n++;

       }

      for(int i=0;i<n;i++)

      {

       System.out.println(st[i]);

      }

    }

}

列出目錄下所有内容

package days15;

import java.io.*;

public class File8 

{

   public static void main(String[]args)

   {

 File dir=new File("D:\\");

 show(dir);

   }

   public static void show(File dir)

   {

File[]files=dir.listFiles();

for(int i=0;i<files.length;i++)

{

if(files[i].isDirectory())

{

show(files[i]);

}

else

{

System.out.println(files[i]);

}

}

   }

}

因為目錄中還有目錄,隻要使用同一個列出目錄功能的函數完成即可,在列出過程中出現的還是目錄的話,,隻要使用同一個列出目錄功能的函數完成即可,在列出過程中出現的還是目錄的話,可以再次調用本功能,也就是函數自身調用自身

這種表現形式或者程式設計手法,稱作遞歸

遞歸應注意:

1、限定條件

2、要注意遞歸的次數,盡量避免記憶體溢出

檔案相關知識綜合

package days15;

import java.io.*;

import java.util.Scanner;

public class Remove 

{

    public static void main(String[]args) throws IOException

    {

     System.out.println("請輸入要操作的路徑:");

     Scanner scr=new Scanner(System.in);

     String str=scr.next();

     File dir=new File(str);//指定檔案路徑

        System.out.println(" 1、指定範圍檔案周遊     2、删除包含該關鍵字的檔案     3、删除以該關鍵字結尾的檔案    4、查找包含該關鍵字的檔案  5、查找以該關鍵字結尾的檔案");

        int x=scr.nextInt();

        String msg=null;

        if(x!=1)

        {

          msg=imp();

        }

        long start=System.currentTimeMillis(); 

        int y=basic(dir,x,msg);

     if((y==4)||(y==5))

     {

     open(dir);

     }

     long end=System.currentTimeMillis();

     long time=end-start;

     if(time<=10000)

     System.out.println("本次執行共花費"+time+"毫秒");

     else

     if(time>10000&&time<=100000)

        System.out.println("本次執行共花費"+time/1000+"秒");

     else

        System.out.println("本次執行共花費"+time/60000+"分鐘");

    }

    //1、檔案周遊     2、删除包含該關鍵字     3、删除以該關鍵字結尾    4、查找包含該關鍵字 5、查找以該關鍵字結尾

    public static int basic(File dir,int x,String msg) throws IOException

    {

       File[]files=dir.listFiles();

     for(int i=0;i<files.length;i++)

     {

         if(files[i].isDirectory())

          basic(files[i],x,msg);

         else

            switch(x)

            {

            case 1:System.out.println(files[i]);break;

            case 2:delete_1(files[i],msg);break;

            case 3:delete_2(files[i],msg);break;

            case 4:find_1(files[i],msg);break;

            case 5:find_2(files[i],msg);break;

            }

     }

    return x;

    }

    public static void delete_1(File dir,String msg) throws IOException//2号功能

    {

     if(dir.toString().contains(msg))//擷取檔案名,包含關鍵字的删除

      {

     System.out.println(dir+"---------------删除成功");

     dir.delete();

      }

    }

    public static void delete_2(File dir,String msg) throws IOException    //3号功能

    {

     if(dir.toString().endsWith(msg))//擷取檔案名,以該關鍵字結尾的删除

      {

     System.out.println(dir+"-----------------删除成功");

     dir.delete();

      }

    }

    public static String[] find_1(File dir,String msg) throws IOException//4号功能

    {

     String[]str=new String[5000];

     int i=0;

     if(dir.toString().contains(msg))//擷取檔案名,包含關鍵字的查找

        {

       System.out.println(dir+"------------查找成功");

        str[i]=dir.toString();

        i++;

        }

     return str;

    }

    public static String[] find_2(File dir,String msg) throws IOException//5号功能

    {

     String[]str=new String[5000];

     int i=0;

     String strs=imp();

     if(dir.toString().endsWith(msg))//擷取檔案名,包含關鍵字的查找

        {

       System.out.println(dir+"---------------查找成功");

        str[i]=dir.toString();

        i++;

        }

     return str;

    }

    public static void open(File f) throws IOException //打開程式

    {

     Runtime r=Runtime.getRuntime();

     r.exec("cmd /k start D:\\");//打開程式

    }

    public static String imp() throws IOException

    {

     System.out.println("請輸入關鍵字資訊:"); //關鍵字

     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        String str = br.readLine();

        return str;

    }

}