第十三章 I/O流

File類
   File對象包含了文件中的所有字節數據,以及文件的其他詳細信息。
   創建File對象
  1. //File對象包含了文件中的所有字節數據,以及文件的其他詳細信息
  2. File file;
  3. //使用絕對路徑創建文件
  4. file = new File("d:/myFile/a/test.txt");
  5. //通過父文件對象創建
  6. file = new File(new File("d:/myFile"), "a/test.txt");
  7. file = new File(new File("d:/myFile/a"),"test.txt");
  8. //通過父文件路徑創建
  9. file = new File("d:/myFile", "a/test.txt");

常見的File的操作
    創建、重命名、刪除、複製、剪切、黏貼

File對象的方法
    exists    判斷文件是否已經存在
    getAbsolutePath   獲取文件的絕對路徑
    isFile 是否是單個的文件
    isDirectory  是否是文件夾
    listFiles     獲取文件夾中的子文件
    createNewFile    創建新文件
    mkdir       創建文件夾
    delete      刪除
    renameTo    重命名


獲取文件的文件名
  1. file.getName();
獲取文件的父文件路徑
  1. file.getParent();
獲取文件的長度(字節數)
  1. file.length();
獲取文件所在盤符的剩餘字節大小
  1. file.getFreeSpace();
獲取文件所在盤符的總大小
  1. file.getTotalSpace();
獲取文件所在盤符的可用空間
  1. file.getUsableSpace();
是否是可執行文件
  1. file.canExecute()
是否可讀
  1. file.canRead();
是否可寫
  1. file.canWrite();
文件最後一次修改的時間
  1. file.lastModified();
  2. //返回long型
  3. long time = file.lastModified();
  4. Date date = new Date(time);
是否是隱藏文件
  1. file.isHidden();
獲取文件中的子文件
  1. File[] files = file.listFile();
獲取當前操作系統的所有盤符
  1. File[] disks = File.listRoots();

刪除文件
    可以用於文件和文件夾,如果是文件夾,並且該文件夾有子文件,則不能刪除,要刪除必須清空文件夾的子文件
  1. file.delete()


操作
查看所有文件的方法
  1. /**
  2. * 查看所有文件的方法
  3. */
  4. public void showFiles(String path){
  5. //根據路徑獲得文件
  6. File file = new File(path);
  7. //判斷文件是否存在
  8. if(file.exists()){
  9. System.out.println(file.getAbsolutePath());
  10. //判斷是否是文件夾
  11. if(file.isDirectory()){
  12.    //如果是文件夾,則獲取文件夾中的子文件
  13.     File[] files = file.listFiles();
  14.    if(files != null){
  15.    //遍歷子文件
  16.    for(File childFile : files){
  17.     //遞歸查看
  18.     showFiles(childFile.getAbsolutePath());
  19.    }    
  20.    }
  21. }
  22. }
  23. }

根據文件類型查找顯示文件
  1. /**
  2. * 根據文件類型查找顯示文件
  3. * @param path
  4. * @param type
  5. */
  6. public void showFiles(String path, String type){
  7. //根據路徑獲得文件
  8. File file = new File(path);
  9. //判斷文件是否存在
  10. if(file.exists()){
  11. //判斷文件是否是文件
  12. if(file.isFile()){
  13. //如果是文件就要判斷文件的後綴名是否和查找的文件類型匹配
  14. if(validateFile(file.getName())){
  15. //獲取文件的後綴名
  16. String fileType = file.getName().substring(file.getName().lastIndexOf(".")+1);
  17. //判斷後綴名是否和查找文件匹配
  18. if(fileType.equalsIgnoreCase(type)){
  19. //打印顯示文件
  20. System.out.println(file.getAbsolutePath());
  21. }
  22. }
  23. }
  24. //如果是文件夾遞歸查找
  25. else{
  26. //如果是文件夾,則獲取文件夾中的子文件
  27. File[] files = file.listFiles();
  28. if(files != null){
  29. //遍歷子文件
  30. for(File childFile : files){
  31. //遞歸查看
  32. showFiles(childFile.getAbsolutePath(),type);
  33. }
  34. }
  35. }
  36. }
  37. }
  38. /**
  39. * 驗證文件是否是一個合法文件
  40. * @return
  41. */
  42. public boolean validateFile(String fileName){
  43. if(fileName.indexOf(".") != -1){
  44. return true;
  45. }
  46. return false;
  47. }

創建單個文件的方法
  1. /**
  2. * 創建單個文件的方法
  3. * @param fileName 新建的文件名
  4. * @param path 創建的位置
  5. */
  6. public void createFile(String fileName, String path){
  7. //根據父文件路徑創建File對象
  8. File parentFile = new File(path);
  9. //判斷父文件是否存在
  10. if(parentFile.exists()){
  11. //判斷父文件是否是文件夾
  12. if(parentFile.isDirectory()){
  13. //構建File對象
  14. File file = new File(path, fileName);
  15. //判斷要新建的文件是否存在
  16. if(!file.exists()){
  17. //創建
  18. try {
  19. file.createNewFile();
  20. } catch (IOException e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. }
  25. else{
  26. JOptionPane.showMessageDialog(null, "該文件已經存在!");
  27. }
  28. }
  29. }
  30. else{
  31. JOptionPane.showMessageDialog(null, "文件夾不存在!");
  32. }
  33. }

創建文件夾的方法
  1. /**
  2. * 創建文件夾的方法
  3. */
  4. public void createDirectory(String fileName, String path){
  5. //new File("").mkdir();
  6. }
  7. /**
  8. * 對文件進行重命名的方法
  9. * @param source 要修改的源文件路徑
  10. * @param fileName 文件的新命名(不包含後綴名)
  11. */
  12. public void reNameFile(String source, String fileName){
  13. File sourceFile = new File(source);
  14. //判斷源文件是否存在
  15. if(sourceFile.exists()){
  16. //判斷源文件是否有後綴名
  17. if(validateFile(sourceFile.getName())){
  18. //獲取源文件的後綴名
  19. String type = sourceFile.getName().substring(sourceFile.getName().lastIndexOf("."));
  20. //根據源文件的路徑以及後綴名創建新命名的文件對象
  21. File file = new File(sourceFile.getParent(),fileName+type);
  22. ////判斷新的文件名是否存在
  23. if(!file.exists()){
  24. //重命名
  25. sourceFile.renameTo(file);
  26. }
  27. }
  28. }
  29. }

刪除文件的方法
  1. /**
  2. * 刪除文件的方法
  3. */
  4. public void deleteFile(String path){
  5. File file = new File(path);
  6. // //刪除文件,可以用於文件和文件夾
  7. // //如果是文件夾,並且該文件夾中有子文件,則不能刪除
  8. // //如有以上情況則必須清空文件夾中的子文件
  9. // file.delete();
  10. //判斷文件是否存在
  11. if(file.exists()){
  12. //判斷文件是否是文件夾
  13. if(file.isDirectory()){
  14. //如果是文件夾獲取子文件
  15. File[] files = file.listFiles();
  16. if(files != null){
  17. //遞歸刪除
  18. for(File childFile : files){
  19. deleteFile(childFile.getAbsolutePath());
  20. }
  21. }
  22. }
  23. //無論是否是文件夾都應刪除當前文件
  24. file.delete();
  25. }
  26. }



IO流
    InputStream           所有輸入流的基類    是一個抽象類
    OutputStream           所有輸出流的基類    也是一個抽象類
    常用的實現類
        FileInputStream                    FileOutputStream
        BufferedInputStream            BufferedOutputStream
   需要通過抽象的實例類才能對文件進行流的讀寫

讀寫
   通過輸入流的read方法讀取文件流的字節信息
   將每次讀取到的信息通過輸出流寫入到新的文件中
  1. int data;
  2. while((data = input.read()) != -1){
  3. output.write(data);
  4. }

JAVA中IO流的分類
1、字節流
        以單字節的方式進行讀取
2、字符流
        以單字符的方式進行讀取

字符流在讀取文本信息時效率高於字節流
字符流由字節流衍生而來,因此必須藉助於字節流實現
字符流不能對單字節構成的文件進行讀寫,如視頻圖片

字符流
       Reader 字符輸入流的基類    抽象類
       Writer    字符輸出類的基類    抽象類
        InputStreamReader             OutputStreamWriter
        BufferedReader                    BufferedWriter   



1、使用字節流讀寫文件中的字節數據
  1. //數據流不能對文件夾進行讀寫
  2. FileInputStream fis = new FileInputStream(new File("d:/a.txt"));
  3. //每次讀取一個字節,因此通過循環反覆讀取字節
  4. int data;
  5. while((data = fis.read()) != -1){
  6. system.out.println(data);
  7. }
  8. fis.close();

2、使用輸出流將字節數據寫入文件
  1. //創建輸出流的時候如果文件不存在,則會自動創建文件,如果文件存在則將默認覆蓋文件
  2. //第二個參數表示是否追加數據,默認爲false
  3. FileOutputStream fos = new FileOutputStream(new File("d:/b.txt"),true);
  4. //寫入數據
  5. fos.write(66);
  6. fos.write(67);
  7. //清空緩衝流
  8. fos.flush();
  9. fos.close();

(優)3、使用緩衝流優化
  1. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("d:/flash.exe")));
  2. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("d:/test.exe")));
  3. int len;
  4. byte[] buffer = new byte[1024];
  5. while((len = bis.read(buffer)) != -1){
  6. bos.write(buffer, 0, len);
  7. }
  8. bis.close();
  9. bos.flush();
  10. bos.close();

(優)4、自定義緩衝流
  1. FileInputStream fis = new FileInputStream(new File("d:/flash.exe"));
  2. FileOutputStream fos = new FileOutputStream(new File("d:/test.exe"));
  3. //讀取長度
  4. int len;
  5. //緩衝數組
  6. byte[] buffer = new byte[1024];
  7. //每次讀取都將字節寫入緩衝區
  8. while((len = fis.read(buffer)) != -1){
  9. //將緩衝區中的數據寫入文件
  10. fos.write(buffer,0,len);
  11. }
  12. fis.close();
  13. fos.flush();
  14. fos.close();


字符流
字符流只適合讀取純文本的File文件,字符流的構建依賴於字節流

使用字符流讀寫文本
  1. try {
  2. InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("d:/a.txt")));
  3. char[] buffer = new char[1024];
  4. StringBuffer str = new StringBuffer();
  5. int len;
  6. while((len = reader.read(buffer)) != -1){
  7. str.append(buffer);
  8. }
  9. reader.close();
  10. System.out.println(str);
  11. } catch (FileNotFoundException e) {
  12. e.printStackTrace();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }

使用字符緩衝流
        InputStreamReader是字節流到字符緩衝流的橋樑
  1. try {
  2. BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("d:/a.txt"))));
  3. String s;
  4. //一次讀取一行
  5. while((s = reader.readLine()) != null){
  6. System.out.println(s);
  7. }
  8. reader.close();
  9. } catch (FileNotFoundException e) {
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  1. try {
  2. BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("d:/b.txt"))));
  3. //使用輸出流寫入數據
  4. writer.write("這是我新建的文本\r\n");
  5. //換行
  6. //writer.newLine();
  7. writer.write("又一段新的內容");
  8. writer.flush();
  9. writer.close();
  10. } catch (FileNotFoundException e) {
  11. e.printStackTrace();
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }


自定義鍵盤接受
  1. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));



序列化 及 反序列化            ObjectInputStream          ObjectOutputStream
       序列化的對象要使用 Serializable接口
  1. import java.io.Serializable;
  2. public class User implements Serializable{
  3. private int userId;
  4. private String name;
  5. public User(int userId, String name) {
  6. super();
  7. this.userId = userId;
  8. this.name = name;
  9. }
  10. public int getUserId() {
  11. return userId;
  12. }
  13. public void setUserId(int userId) {
  14. this.userId = userId;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. }
添加兩個實例對象(user)到 list 集合裏
  1. User user1 = new User(1001, "tom");
  2. User user2 = new User(1002, "jack");
  3. ArrayList<User> list = new ArrayList<User>();
  4. list.add(user1);
  5. list.add(user2);
進行序列化保存
  1. try {
  2. ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(new File("d:/users.data")));
  3. //將對象通過輸出流進行序列化保存
  4. //序列化對象必須實現序列化接口
  5. output.writeObject(list);
  6. output.flush();
  7. output.close();
  8. } catch (Exception e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }

反序列化讀取文件
  1. try {
  2. ObjectInputStream input = new ObjectInputStream(new FileInputStream(new File("d:/users.data")));
  3. ArrayList<User> list = (ArrayList<User>) input.readObject();
  4. input.close();
  5. for(User user : list){
  6. System.out.println(user.getUserId()+"\t"+user.getName());
  7. }
  8. } catch (FileNotFoundException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. } catch (ClassNotFoundException e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }


發佈了46 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章