詳談JAVA中的file類與IO流


File類
位於java.io包
構造方法:
File(String parent, String child)
new file("d:\\","a.txt");

File(String pathname)
new file("d:\\a.txt");

File(File parent, String child)
File f = new File("d:\\");
File f1=new File(f,"a.txt");

常用方法:
1.獲取
1)文件名
String getName()
2)文件路徑
String getAbsolutePath()
3)大小
long length()
3)最后修改時間
long lastModified()

1 File file=new File("d:\\aa.txt");
2 System.out.println(file.getName());
3 System.out.println(file.getAbsolutePath());
4 System.out.println(file.lastModified());
5 
6 long l=file.lastModified();
7 Date date=new Date(l);
8 System.out.println(date.toString());
9 System.out.println(file.length());

2.創建與刪除
1)創建文件
boolean createNewFile()
2)創建文件夾(目錄)
boolean mkdir() 單層
boolean mkdirs() 多層
3)刪除文件和目錄
boolean delete()

1 File f=new File("d:\\b.txt");
2 boolean b=f.createNewFile();
3 System.out.println(b);
4 f.delete();
1 File f1=new File("d:\\ch1027");
2 f1.mkdir();//建立單層目錄
3 File f2=new File("d:\\ch1028\\ch1029\\ch1030");
4 f2.mkdirs();//建立多層目錄
5 
6 f2.delete();//刪除的是ch1030文件夾

3.判斷
boolean isDirectory() 測試此抽象路徑名表示的文件是否是一個目錄。
boolean isFile() 測試此抽象路徑名表示的文件是否是一個標准文件。
boolean isHidden() 測試此抽象路徑名指定的文件是否是一個隱藏文件。 

1 File f1=new File("d:\\ch1027");
2 System.out.println(f1.isDirectory());
3 System.out.println(f1.isFile());
4 
5 File f= new File("d:\\bb.txt");
6 boolean b = f.createNewFile();
7 System.out.println(f.isHidden());//false,默認不隱藏

4.重命名
boolean renameTo(File dest)
1)同目錄 ---- 改名
2)不同目錄 ----- 相當於剪切

1 File f= new File("f:\\bb6.txt");
2 File f1= new File("f:\\123\\bb6.txt");
3 System.out.println(f.renameTo(f1));

5.其它
static File[] listRoots() 列出可用的文件系統根。
long getFreeSpace() 可用空間
long getTotalSpace() 總容量
String[] list() 列出目錄中的文件和目錄(同輩目錄)

 1 //遍歷出文件系統根目錄
 2 File[] files = File.listRoots();
 3 for(int i=0;i<files.length;i++){
 4 System.out.println(files[i]);
 5 }
 6 
 7 //遍歷目錄中的文件和目錄
 8 File f= new File("f:\\123");
 9 String [] strs = f.list();
10 for(int i=0;i<strs.length;i++){
11 System.out.println(strs[i]);
12 }

FileFilter接口 
文件過濾器
例子:顯示出某個目錄下的,非隱藏文件
File[] listFiles(FileFilter filter)
參數是一個過濾器類
詳見下面程序

//新建一個過濾非隱藏文件的過濾器,需要實現FileFilter接口
public class FilteHidden implements FileFilter{
    public boolean accept(File file) {    
        return !file.isHidden();
    }
}
//新建一個文件類
public class Filess {    
    public static void main(String[] args) {
        File file = new File("f:\\123");
        File [] s = file.listFiles(new FilteHidden());//返回的是過濾后的元素
        for(int i=0;i<s.length;i++){//遍歷輸出每個元素的名字
            System.out.println(s[i].getName());
        }
    }
}    

 

FilenameFilter 接口
文件名過濾器
例子:對文件名進行過濾
File[] listFiles(FilenameFilter filter)
參數是一個過濾器類
詳見下面程序

 1 //創建一個文件名過濾器
 2 public class Filename implements FilenameFilter{
 3     private String endstr;
 4     public boolean accept(File dir, String name) {
 5         return name.endsWith(endstr);//返回符合輸入格式的文件
 6     }
 7     Filename(String str){//傳入代表文件格式的字符串
 8         endstr = str;
 9     }
10 }
11 
12 public class FilenameDemo {    
13     public static void main(String[] args) {
14         File file= new File("f:\\123");
15         File [] files = file.listFiles(new Filename(".txt"));
16         //遍歷結果
17         for(int i=0;i<files.length;i++){    
18             System.out.println(files[i].getName());
19         }    
20     }
21 }

 

File類得到文件列表的方法
1)列出所有文件
File file = new File(“f:\\aa”);
File [] filearr = file.listFiles(); 表示的目錄中的(文件及目錄)
String [] filearr= file.list(); 表示的目錄中的(文件及目錄)
2)過濾器
File file = new File(“f:\\aa”);
FilenameFilter接口,用於過濾文件名。
String[] filenamearr= file.list(FilenameFilter filter)
File[] filenamearr = file.listFiles(FilenameFilter filter)

File file = new File(“f:\\aa”);
FileFilter接口,用於過濾文件。
File[] filearr = file.listFiles(FileFilter filter)

遞歸:自已(方法)調用自已
例子:用遞歸把目錄下所有的目錄及文件全部顯示出來

 1 public class B {
 2     public static void main(String[] args) {
 3         File file = new File("f:\\123");
 4         listAllFile(file);
 5     }
 6 
 7     public static void listAllFile(File file) {
 8         File[] strs = file.listFiles();
 9         for (int i = 0; i < strs.length; i++) {
10             // 判斷strs[i]是不是目錄
11             if (strs[i].isDirectory()) {
12                 listAllFile(strs[i]);//遞歸調用自己
13                 System.out.println("目錄="+strs[i].getName());
14             } else {
15                 System.out.println("文件名="+strs[i].getName());
16             }
17         }    
18     }
19 }       

 

IO流
IO流:輸入(Input)輸出(Output)流
位置於java.io包下
流作用:讀寫文件用的
流分類
1)按流向分(以內存為參照物):
輸入流 輸出流
2)按流的內容分:
字節流(能讀寫所有文件),字符流(讀取純文本文件)
3)按功能分:
節點流 處理流(套在節點流上的)
字節流,它的子類都是Stream
字符流,它的子類是Writer Reader

 

FileWriter
文件字符輸出流
構造方法:
注意:1)對象一創建出來就得給文件路徑。
2)如果文件存在就覆蓋,不存在則創建
3)不想覆蓋,是用下面的構造方法
FileWriter(String fileName, true)
4)寫完后要flush()
5)寫完要關閉流

 1 /**
 2 *文件字符輸出流實例
 3 */
 4 public class FileWriterDemo {
 5     public static void main(String[] args) {
 6         FileWriter fw = null;
 7         try {
 8             fw = new FileWriter("d:\\1.txt");
 9             fw.write("fff");
10             fw.write("ggggg");
11             fw.flush();
12             int i = 10/0;//故意產生錯誤
13         } catch (Exception e) {
14             String str = e.getMessage();
15             FileWriterDemo d = new FileWriterDemo();
16             d.xie(str);//錯誤信息寫入另一個文件中。
17             e.printStackTrace(); 
18         } finally {
19             try {
20                 fw.close();
21             } catch (IOException e) {
22                 e.printStackTrace();
23            }
24         }
25     }
26 
27     public void xie(String str) {
28         FileWriter fw = null;
29         try {
30             fw = new FileWriter("d:\\2.txt", true);
31             fw.write(str);
32             fw.flush();
33         } catch (IOException e) {
34             e.printStackTrace();
35         } finally {
36             try {
37                 fw.close();
38             } catch (IOException e) {
39                 e.printStackTrace();
40             }
41         }
42     }
43 }

 


FileReader
文件字符輸入流
代碼演示:

 1 /**
 2 *文件字符輸入流實例
 3 */
 4 public static void main(String[] args) {    
 5     try {
 6         FileReader fr = new FileReader("f:\\1.txt");
 7         char[] buf= new char[3];
 8         int i = fr.read(buf);
 9         System.out.println(new String(buf,0,i)); 
10         /*new String(buf,0,i) char [] buf,從char數組的第幾個位置開始讀,讀幾個*/
11     } catch (Exception e) {
12         e.printStackTrace();
13     }    
14 }



BufferedWriter 帶緩沖區的文件字符輸出流
特點:1)它是處理流,要包在節點流外面來使用
2)提高寫的效率
3)換行newLine()
創建對象:
1)FileWriter fw = new FileWriter("d:\\cc\\cc.txt");
BufferedWriter bw = new BufferedWriter(fw);
2)沒有捕獲異常時
BufferedWriter bw1 = new BufferedWriter(new FileWriter("d:\\cc\\cc3.txt"));
bw1.write("abcbbbb");
bw1.newLine();
bw1.write("sssss");
bw1.newLine();
bw1.write("defxxx");
bw1.flush();
bw1.close();


BufferedReader 帶緩沖區的文件字符輸入流
特點:1)它是處理流,要包在節點流外面來使用
2)提高讀取的效率
3)讀一行readLine()
創建對象:
try {
  BufferedReader br= new BufferedReader(new FileReader("d:\\cc\\cc.txt"));
  String str=null;
  while( (str=br.readLine()) != null){
    System.out.println(str);
} catch (Exception e) {
   e.printStackTrace();
}


文件的復制:

public static void main(String[] args) {
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {    
        br = new BufferedReader(new FileReader(new File("d:\\cc\\cc.txt")));
        bw = new BufferedWriter(new FileWriter("d:\\cc\\cc5.txt"));
        String str = null;//臨時接收讀寫的字符串
        while ((str = br.readLine()) != null) {
            bw.write(str);
            bw.newLine();
            bw.flush();
     } catch (Exception e) {
         e.printStackTrace();
     } finally {
        if (br != null) {
            try {
               br.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
        }
        if (bw != null) {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    
}

 

FileOutputStream 文件字節輸出流
特點:1)輸出的是字節
2)不用flush()

 1 public static void main(String[] args) {
 2     FileOutputStream fos=null;
 3     try{
 4         fos = new FileOutputStream("d:\\cc\\cc8.txt");
 5         fos.write("abc".getBytes());
 6         //getBytes()將一個字符串轉化為一個字節數組byte[]的方法
 7         fos.write(97);
 8     }catch (Exception e) {
 9         e.printStackTrace();
10     }finally{
11         if(fos != null){
12              try {
13                fos.close();
14             } catch (IOException e) {
15                e.printStackTrace();
16             }
17         }
18     }
19 }    

FileInputStream 文件字節輸入流
特點:1)輸入的是字節
2)不用flush()

 1 public static void main(String[] args) {
 2     try {
 3         FileInputStream fis = new FileInputStream("d:\\cc\\cc8.txt");
 4         byte [] b = new byte[2];//存儲臨時數據
 5         int len=0;
 6         while( (len =fis.read(b)) != -1){
 7             System.out.println(new String(b,0,len));
 8         }
 9     }catch (Exception e) {
10         e.printStackTrace();
11     }
12 }

 

BufferedOutputStream BufferedInputStream
帶緩沖區的字節輸出(輸入)流
特點:1)輸出(入)的是字節
2)是個處理流
2)用flush()

 

 1 /**
 2 *字節流實現的復制功能
 3 */
 4 public static void main(String[] args) {
 5     try {
 6         BufferedInputStream bis= new BufferedInputStream( new  FileInputStream("d:\\cc\\cc8.txt"));
 7         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\cc\\cc9.txt"));
 8         int len=0;
 9         byte [] b = new byte[1024];
10         while( (len = bis.read(b)) !=-1 ){
11             bos.write(b);
12         }
13         bos.flush();
14     } catch (Exception e) {
15         e.printStackTrace();
16     }finally{//加close()方法,請參考(上面文件的復制部分)}
17 }

 

System.in
從鍵盤輸入得到一個流InputStream
可以使用InputStream中的方法

 1 public static void main(String[] args) {
 2     InputStream is = System.in;
 3     int ch = 0;
 4     try {
 5         while ((ch = is.read()) != -1) {
 6         System.out.println((char) ch); //
 7        }
 8     } catch (IOException e) {
 9         e.printStackTrace();
10     }
11 }

 

ObjectInputStream ObjectOutputStream
對象的輸入 輸出流
特點:1)寫入很多數據類型
2)寫入自定義對象


序列化:把對象存入硬盤中(屬性的值)
反序列化:把對象從硬盤中取出來(屬性的值)
注意: 1)static 修飾的屬性不能存入
2)Transient修飾的屬性不能存入//transient關鍵字的作用:標記的成員變量不參與序列化過程
3)對象對應的類必須要實現一個接口(空接口)Serializable接口
4)不用flush()
5)類中的方法不能被序列化,只能序列化屬性
程序演示:

 1 public static void main(String[] args) {
 2     try {
 3         ObjectOutputStream ous = new ObjectOutputStream(new FileOutputStream(new File("d:\\cc\\Animal.obj")));
 4         Animal a1= new Animal("aa",1);//Animal類是自定義的,這里未寫出
 5         ous.writeObject(a1);//序列化
 6         ous.close();
 7 
 8         ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:\\cc\\Animal.obj")));
 9         Animal an=(Animal)ois.readObject();//反序列化
10         System.out.println(an.getAge()+","+an.getName());
11         ois.close();
12     } catch (Exception e) {
13         e.printStackTrace();
14     }
15 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM