溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java中IO流對(duì)文件操作的案例

發(fā)布時(shí)間:2020-10-28 15:01:23 來源:億速云 閱讀:157 作者:小新 欄目:編程語言

這篇文章主要介紹java中IO流對(duì)文件操作的案例,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

Io流

按照分類 有兩種分類

流向方向: 有輸入流和輸出流

按照操作類型有:字節(jié)流和字符流

按照流向方向

字節(jié)流的一些操作    
        //讀文件
        FileInputStream fis = new FileInputStream("java.txt");
        int temp = fis.read()//一次讀取一個(gè)字節(jié)
        System.out.println(temp); //打印的字母的碼值  讀取完返回-1
        System.out.println((char)temp);//打印字母
        
        
        byte[] arr = new byte[6]; //定義byte數(shù)組告訴系統(tǒng)一次讀取幾個(gè)字節(jié),減少內(nèi)存和硬盤之間的通信,可以提高效率
        int temp = bis.read(arr); //有參的read方法返回的int值是讀取了幾個(gè)字節(jié)
        System.out.println(new String(arr, 0, temp)); // 
        
        //寫文件
        FileOutputStream fos = new FileOutputStream("file" + File.separator + "1024.txt",true);
            //如果該文件不存在,則會(huì)自動(dòng)創(chuàng)建
            //傳入true會(huì)在文件內(nèi)容的后面寫入文字,而不會(huì)覆蓋之前的內(nèi)容
            //開發(fā)中文件分隔符最好不要直接寫\  而是寫 File.separator
            
        
        String msg = "Hello World";
        fos.write("\n".getBytes());//換行,并向文件寫入  String.getBytes() 因?yàn)橐宰止?jié)的形式傳入
        fos.write(msg.getBytes());
        
        
        String msg = "好好學(xué)習(xí)";
        //一個(gè)漢字占2個(gè)字節(jié),向里面一次傳入3個(gè)字節(jié)會(huì)導(dǎo)致亂碼
        fos.write(msg.getBytes(), 0, 3);
        
        
        byte[] arr = new byte[6];//一次性寫這么多字節(jié)
        int temp = fis.read(arr);
        fos.write(arr, 0, temp);

        fos.flush();//刷新
        
        
        //新的jdk7寫法是在try括號(hào)()里面寫文件的鏈接, 這樣最后就不用關(guān)閉了,會(huì)自動(dòng)關(guān)閉
        
        //緩沖輸入流底層默認(rèn)創(chuàng)建一個(gè)大小是8192長(zhǎng)度的byte數(shù)組
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("java.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("file" + File.separator + "good.txt"));
        
        int temp = bis.read();//temp依然為ascii瑪  每次一個(gè)

一些練習(xí)

利用BufferedInputStream 和 BufferedOutputStream 實(shí)現(xiàn)將一個(gè)文件copy到另一個(gè)文件

package com.wpbxx.stream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferFileCopy {

    public static void main(String[] args) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("java.txt"));
            bos = new BufferedOutputStream(new FileOutputStream("file" + File.separator + "good.txt"));
            int temp;
            while((temp = bis.read()) != -1){
                bos.write(temp);
            }
            bos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
        
    }

}

文件的加密  將一個(gè)字節(jié)異或一個(gè)數(shù)字實(shí)現(xiàn) 在傳輸時(shí)進(jìn)行文件的加密

package com.wpbxx.stream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CodeFile {

    public static void main(String[] args) {
        //jdk7新寫法
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("圖片.png"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("code.png"));
                ) {
            
            int temp;
            while((temp = bis.read()) != -1){
                bos.write(temp ^ 88);
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

文件解密

package com.wpbxx.stream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DecodeFile {

    public static void main(String[] args) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("code.png"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("decode.png"));) {
            int temp;
            while ((temp = bis.read()) != -1) {
                bos.write(temp ^ 88);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

字符流的一些操作  可以解決亂碼的問題

//讀
        //注意:字符流不能讀取非文本文件
        FileReader fr = new FileReader("java.txt");
        int temp;
        while ((temp = fr.read()) != -1) {
            System.out.println((char) temp); //一次一個(gè)字符
        }
        //使用緩沖字符流
        BufferedReader br = new BufferedReader(new FileReader("word.txt"));
        String msg;
        while((msg = br.readLine()) != null){  //一次可以讀取一行
            System.out.println(msg); 
        }
        //寫
        FileWriter fw = new FileWriter("word.txt");
        fw.write("我喜歡學(xué)習(xí)java");
        fw.write(97);
        
        BufferedWriter bw = new BufferedWriter(new FileWriter("newbuffered.txt"));
        bw.write("你好");
        bw.newLine();//回車換行
        bw.write("java");

同樣是copy文件

package com.wpbxx.chario;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
 * 使用緩沖流拷貝文件
 * 注意:字符流不能讀取非文本文件
 */
public class BufferFileCopy {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("java.txt"));
            BufferedWriter bw = new BufferedWriter(new FileWriter("file" + File.separator + "hellojava.txt"));    
                ) {
            String msg;
            while((msg = br.readLine()) != null){
                bw.write(msg);
                bw.newLine();
            }
            bw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

}

通過java中的File類實(shí)現(xiàn)對(duì)文件的一些操作

File file1 = new File("D:\\hello.txt");
        //如果文件存在,就不創(chuàng)建了,返回false,如果不存在就會(huì)創(chuàng)建,返回true
        System.out.println(file1.createNewFile());
        
        File file2 = new File("D:\\new");
        //如果文件夾存在,就不創(chuàng)建了,返回false,如果不存在就會(huì)創(chuàng)建,返回true
        System.out.println(file2.mkdir());
        
        File file3 = new File("D:\\wpbxx\\1024");
        //可以創(chuàng)建多級(jí)目錄,如果文件夾存在,就不創(chuàng)建了,返回false,如果不存在就會(huì)創(chuàng)建,返回true
        System.out.println(file3.mkdirs());
        
        File file4 = new File("D:\\wpbxx\\1024.txt");
        //只能創(chuàng)建文件夾
        System.out.println(file4.mkdirs());
        
        File file5 = new File("1026.txt");
        //如果不寫盤符,會(huì)默認(rèn)在項(xiàng)目的根目錄里面創(chuàng)建
        System.out.println(file5.createNewFile());
        System.out.println(file5.exists());
        
        //舊名字
        File oldFile1 = new File("D:\\world.txt");
        //新名字
        File newFile1 = new File("D:\\wpbxx\\java.txt");
        //如果兩個(gè)文件路徑不一致,則會(huì)將舊文件剪切到新的文件路徑中再重命名
        oldFile1.renameTo(newFile1);
        
        
        //不會(huì)將文件放到回收站中,而是直接刪除
        File del = new File("D:\\wpbxx\\java.txt");
        
        File del1 = new File("D:\\wpbxx");
        //如果文件夾下有其他文件,則不會(huì)刪除
        System.out.println(del1.delete());
        
                File file2 = new File("D:\\new.txt");
        //判斷是否是文件夾
        System.out.println(file2.isDirectory());
        //判斷是否是文件
        System.out.println(file2.isFile());
        
        //判斷文件是否存在
        System.out.println(file2.exists());
        
        File file3 = new File("D:\\hidden");
        //判斷文件是否隱藏
        System.out.println(file3.isHidden());
        
        
        File file1 = new File("1024.txt");
        //查看絕對(duì)路徑
        System.out.println(file1.getAbsolutePath());
        //文件的大小,單位是字節(jié)
        System.out.println(file1.length());
        //最后修改時(shí)間
        Date date = new Date(file1.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(date));
        
        File file2 = new File("F:\\wpbxx\\代碼\\code\\chapter-08");
        //獲取目錄下的同級(jí)文件或文件夾的名稱
        String[] nameArray = file2.list();
        for(String name : nameArray){
            System.out.println(name);
        }

幾個(gè)小練習(xí)

package com.wpbxx.exercise;

import java.io.File;
import java.util.Scanner;

/**
 * 問題:從鍵盤接收一個(gè)路徑,將這個(gè)路徑下的所有文件和文件夾的名字按照層級(jí)打印。
 * 例如:
 *    wpbxx
 *              java
 *                  XXX.java
 *                  XXX.jpg
 *              php
 *                  XXX.php
 *              readme.txt
 * 
 * 分析:獲取路徑File對(duì)象中的File數(shù)組
 *     遍歷數(shù)組,取得File對(duì)象
 *     打印文件或文件夾的名字
 *     如果是一個(gè)文件夾的話,使用遞歸重復(fù)上面的操作
 */
public class FileNames {
    
    //用來記錄縮進(jìn)的次數(shù)
    private static int count = 0;

    public static void main(String[] args) {
        
        File file = getFile();
        
        getFileNames(file);
    }
    
    //每次調(diào)用該方法時(shí),說明進(jìn)入到一個(gè)新的文件夾的內(nèi)部,需要增加一個(gè)縮進(jìn)
    private static void getFileNames(File file) {
        //獲取路徑File對(duì)象中的File數(shù)組
        File[] fileArray = file.listFiles();
        
        //遍歷數(shù)組,取得File對(duì)象
        for(int i=0; i<fileArray.length; i++){
            
            //通過遍歷count來控制打印幾個(gè)縮進(jìn)
            for(int j=0; j<count; j++){
                System.out.print("\t");
            }
            
            //打印文件或文件夾的名字
            System.out.println(fileArray[i]);
            
            
            
            //如果是一個(gè)文件夾的話,使用遞歸重復(fù)上面的操作
            if(fileArray[i].isDirectory()){
                count++;
                getFileNames(fileArray[i]);//數(shù)組遍歷完最后一個(gè)File對(duì)象時(shí),說明當(dāng)前文件夾已經(jīng)遍歷結(jié)束,需要做自減運(yùn)算
                count--;
            }
            
        }
    }
    
    //獲取用戶輸入路徑的File對(duì)象
    private static File getFile() {
        
        System.out.println("請(qǐng)輸入一個(gè)文件夾路徑:");
        
        Scanner sc = new Scanner(System.in);
        //獲取用戶輸入的路徑,用戶輸入的路徑有可能是錯(cuò)誤的,需要進(jìn)行判斷
        while(true){
            String input = sc.nextLine();
            File file = new File(input);
            if(!file.exists()){
                System.out.println("您輸入的文件路徑有誤,請(qǐng)重新輸入文件路徑:");
            }else if(file.isFile()){
                //如果用戶輸入的路徑是一個(gè)文件
                System.out.println("您輸入的路徑是一個(gè)文件,請(qǐng)輸入一個(gè)文件夾的路徑");
            }else{
                return file;
            }
        }
    }
    
    

}
package com.wpbxx.exercise;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 問題:收費(fèi)版軟件有試用次數(shù),利用IO流的知識(shí),模擬一個(gè)可以試用3次的功能,打開3次之后提示用戶購(gòu)買正版軟件
 * 
 * 分析:將試用的次數(shù)做加密處理后寫到txt文件中
 *     使用IO流相關(guān)的知識(shí)將txt文件中的內(nèi)容讀取到內(nèi)存中
 *     如果讀取的內(nèi)容小于0時(shí)提示用戶購(gòu)買正版軟件
 *     如果大于0小于等于3時(shí),將試用次數(shù)做自減運(yùn)算之后寫出到txt文件中
 */
public class Trial {

    public static void main(String[] args) {
        //code();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("src" + File.separator + "com"
                    + File.separator + "monkey1024" + File.separator + "exercise" + File.separator + "config.txt"));
            int temp = bis.read();
            //解密處理
            int count = temp ^ 66;
            if(count > 0 && count <= 3){
                count--;
                System.out.println("您的試用次數(shù)還剩余" + count + "次");
                bos = new BufferedOutputStream(new FileOutputStream("src" + File.separator + "com"
                        + File.separator + "monkey1024" + File.separator + "exercise" + File.separator + "config.txt"));
                //做加密處理
                bos.write(count ^ 66);
                bos.flush();
            }else{
                System.out.println("您的試用次數(shù)已超出限制,請(qǐng)購(gòu)買正版軟件!");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                //避免出現(xiàn)空指針
                if(bis != null){
                    bis.close();
                }
                if(bos != null){
                    bos.close();
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    //試用次數(shù)加密處理
    private static void code() {
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream("src" + File.separator + "com"
                    + File.separator + "monkey1024" + File.separator + "exercise" + File.separator + "config.txt"));
            //加密處理
            bos.write(3 ^ 66);
            bos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                //避免出現(xiàn)空指針異常
                if(bos != null){
                    bos.close();
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
package com.wpbxx.exercise;
import java.io.File;
/**
 * 問題:統(tǒng)計(jì)項(xiàng)目根目錄下以.txt結(jié)尾的文件數(shù)量,并將文件名打印出來
 * 分析:獲取項(xiàng)目根目錄下的文件名
 *     對(duì)文件名進(jìn)行判斷是否是以.txt結(jié)尾
 */
public class FindTxt {
    public static void main(String[] args) {
        File file = new File("F:\\wpbxx\\01-JavaSE\\代碼\\code\\chapter-08");
        File[] fileArray = file.listFiles(); //返回一個(gè)File列表就是該目錄下的File列表
        
        //統(tǒng)計(jì)出現(xiàn)次數(shù)
        int count = 0;
        for(File name : fileArray){
            String s = name.toString();
            
            //判斷是否是以.txt文件結(jié)尾
            if(s.endsWith(".txt")){
                if(name.isFile()){
                    count++;
                    System.out.println(name);
                }
            }
        }
        
        System.out.println("以.txt文件結(jié)尾的數(shù)量是" + count + "個(gè)");
        
    }
}
package com.monkey1024.file;

import java.io.File;
import java.io.FilenameFilter;

/**
 * 問題:統(tǒng)計(jì)項(xiàng)目根目錄下以.txt結(jié)尾的文件數(shù)量,并將文件名打印出來
 * 使用文件過濾器實(shí)現(xiàn)上述需求
 */
public class FilenameFilterTest01 {

    public static void main(String[] args) {
        File file = new File("F:\\monkey1024\\01-JavaSE\\代碼\\code\\chapter-08");
        String[] nameArray = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name){
                //獲取根目錄下每個(gè)文件的File對(duì)象
                File file1 = new File(dir, name);
                //編寫篩選條件
                return file1.isFile() && file1.getName().endsWith(".txt");
            }
        });
        
        System.out.println("以.txt結(jié)尾的文件個(gè)數(shù)是" + nameArray.length + "個(gè)");
        
        for(String name : nameArray){
            System.out.println(name);
        }
    }

}
package com.wpbxx.file;
import java.io.File;
import java.io.FilenameFilter;
/**
 * 問題:統(tǒng)計(jì)項(xiàng)目根目錄下以.txt結(jié)尾的文件數(shù)量,并將文件名打印出來
 * 使用文件過濾器實(shí)現(xiàn)上述需求
 */
public class FilenameFilterTest01 {
    public static void main(String[] args) {
        File file = new File("F:\\wpbxx\\01-JavaSE\\代碼\\code\\chapter-08");
        String[] nameArray = file.list(new FilenameFilter() {//重寫accept方法  
            @Override
            public boolean accept(File dir, String name){//將過濾的規(guī)則寫進(jìn)來
                //獲取根目錄下每個(gè)文件的File對(duì)象
                File file1 = new File(dir, name);
                //編寫篩選條件
                return file1.isFile() && file1.getName().endsWith(".txt");
            }
        });
        System.out.println("以.txt結(jié)尾的文件個(gè)數(shù)是" + nameArray.length + "個(gè)");
        for(String name : nameArray){
            System.out.println(name);
        }
    }
}

對(duì)對(duì)象的讀取

為啥要對(duì)對(duì)象讀???

平時(shí)我們?cè)贘ava內(nèi)存中的對(duì)象,是無 法進(jìn)行IO操作或者網(wǎng)絡(luò)通信的,因?yàn)樵谶M(jìn)行IO操作或者網(wǎng)絡(luò)通信的時(shí)候,人家根本不知道內(nèi)存中的對(duì)象是個(gè)什么東西,因此必須將對(duì)象以某種方式表示出來,即 存儲(chǔ)對(duì)象中的狀態(tài)。一個(gè)Java對(duì)象的表示有各種各樣的方式,Java本身也提供給了用戶一種表示對(duì)象的方式,那就是序列化。換句話說,序列化只是表示對(duì) 象的一種方式而已。OK,有了序列化,那么必然有反序列化,我們先看一下序列化、反序列化是什么意思。

序列化:將一個(gè)對(duì)象轉(zhuǎn)換成一串二進(jìn)制表示的字節(jié)數(shù)組,通過保存或轉(zhuǎn)移這些字節(jié)數(shù)據(jù)來達(dá)到持久化的目的。

反序列化:將字節(jié)數(shù)組重新構(gòu)造成對(duì)象。

序列化只需要實(shí)現(xiàn)java.io.Serializable接口就可以了。序列化的時(shí)候有一個(gè)serialVersionUID參數(shù),Java序列化機(jī)制是通過在運(yùn)行時(shí)判斷類的serialVersionUID來驗(yàn)證版本一致性的。 在進(jìn)行反序列化,Java虛擬機(jī)會(huì)把傳過來的字節(jié)流中的serialVersionUID和本地相應(yīng)實(shí)體類的serialVersionUID進(jìn)行比較, 如果相同就認(rèn)為是一致的實(shí)體類,可以進(jìn)行反序列化,否則Java虛擬機(jī)會(huì)拒絕對(duì)這個(gè)實(shí)體類進(jìn)行反序列化并拋出異常。serialVersionUID有兩 種生成方式:

如果一個(gè)類的對(duì)象支持序列化和反序列化,需要實(shí)現(xiàn)Serializable,Serializable中沒有任何方法,只是相當(dāng)于一個(gè)標(biāo)記

有一個(gè)類

package com.monkey1024.serializable;

import java.io.Serializable;

/**
 * 如果一個(gè)類的對(duì)象支持序列化和反序列化,需要實(shí)現(xiàn)Serializable
 * Serializable中沒有任何方法
 */
public class Student implements Serializable{
    
    
    /**
     * 自動(dòng)生成序列化版本號(hào)
     */
    private static final long serialVersionUID = -716323668524282676L;

    private String name;
    
    //添加屬性后,使用反序列化時(shí)會(huì)報(bào)出InvalidClassException
    //transient修飾的變量不會(huì)被序列化
    transient private int age;
    
    private boolean sex;
    
    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}

然后我們對(duì)這個(gè)類進(jìn)行序列化和反序列化

Student zhangsan = new Student();
        zhangsan.setName("張三");
        zhangsan.setAge(20);
        //寫
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("zhangsan"));
        oos.writeObject(zhangsan);
        oos.flush();
        
        //讀
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("zhangsan"));
        Student s = (Student)ois.readObject();
        System.out.println(s.getName());
        System.out.println(s.getAge());

以上是java中IO流對(duì)文件操作的案例的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI