java檔案操作總結,java檔案總結

來源:互聯網
上載者:User

java檔案操作總結,java檔案總結

RandomAccessFile 相關API的使用

    pointer=0; 檔案指標        寫方法 raf.write(int) -->唯寫一個位元組 後8位,同時指標指向下一個位置,準備再次寫入        讀方法 int b = raf.read()-->讀一個位元組        讀寫檔案完成後一定要關閉
    public static void testrandomaccessfile() throws IOException {        File demo=new File("demo");        if(!demo.exists())            demo.mkdir();        File file=new File(demo,"raf.dat");        if(!file.exists())            file.createNewFile();        RandomAccessFile raf=new RandomAccessFile(file,"rw");        //指標位置        System.out.println(raf.getFilePointer());        raf.write('A');//唯寫了一個位元組        System.out.println(raf.getFilePointer());        raf.write('B');        int i=0x7fffffff;        //用write方法 每次只能寫一個位元組,如果要把i寫進去就得寫4次        raf.write(i>>>24);//高8位        raf.write(i>>>16);        raf.write(i>>>8);        raf.write(i);        System.out.println(raf.getFilePointer());        //可以直接寫一個int        raf.writeInt(i);        String s ="中";        byte[] gbk=s.getBytes("gbk");        raf.write(gbk);//寫入位元組數組        System.out.println(raf.length());        //讀檔案必須把指標移到頭部        raf.seek(0);        //一次性讀取。把檔案中內容讀取到位元組數組中        byte[] buf=new byte[(int)raf.length()];        raf.read(buf);        System.out.println(Arrays.toString(buf));        for(byte b:buf){            System.out.println(Integer.toHexString(b&0xff)+" ");        }        raf.close();    }

writeInt()方法源碼,每次寫入一位


image.png

IO流(輸入資料流,輸出資料流)
位元組流,字元流
1.位元組流
1)InputStream、OutputStream
InputStream抽象了應用程式讀取資料的方式
OutputStream抽象了應用程式寫出資料的方式
2)EOF=End 讀到-1就讀到結尾
3)輸入資料流基本方法
int b=in.read(); 讀取一個位元組無符號填充到int的低八位。-1是EOF
in.read(byte[] buf)讀取資料填充到位元組數組buf
in.read(byte[] buf,int start,int size)讀取資料填充到位元組數組buf,從buf的start位置開始,存放size長度的資料
4)輸出資料流基本方法
out.write(int b)寫出一個byte到流,b的低8位
out.write(byte[] buf)將buf位元組數組都寫入到流
out.write(byte[] buf,int start,int size)
5)FileInputStream--->具體實現了在檔案上讀取資料
6)FileOutputStream 實現了向檔案中寫出byte資料的方法
7)DataOutputStream/DataInputStream
對流功能的擴充,可以更加方便的讀取Int,long,字元等類型資料
DataOutputStream
writeInt()/writeDouble()/writeUTF()
DataOutputStream dos=new DataOutputStream(new FileOutputStream(file));
8)BufferedInputStream&BufferedOutputStream
這兩個流類為IO提供了帶緩衝區的操作,一般開啟檔案進行寫入或讀取操作時,都會加上緩衝,這種流模式提高了IO的效能

從應用程式中把輸入放入檔案,相當於將一缸水倒入到另一個缸中:
FileOutputStream--->write方法黨羽與一滴一滴把水轉移過去
DataOutputStream--->writexxx()方法會方便一些,相當於一瓢一瓢轉移
BufferedOutputStream--->write方法更方便,相當於一瓢一瓢水先放入桶中,再從桶中匯入到另一個缸中

使用in.read()方法

    /*    讀取指定檔案內容,按照16進位輸出到控制台    並且每輸出10個byte換行     */    public static void printHex(String filename) throws IOException {        //把檔案作為位元組流進行讀操作        FileInputStream in=new FileInputStream(filename);        int b;        int i=1;        while((b=in.read())!=-1){            if(b<=0xf) {                //單位元前面補0                System.out.print("0");            }            System.out.print(Integer.toHexString(b)+" ");//將整形b轉換為16進位的字串            if(i++%10==0)                System.out.println();        }        in.close();    }

使用in.read(byte[] buf , int start , int size)
將資料讀取到位元組數組中,返回資料大小,迴圈輸出位元組數組

 public static void printHexByByteArray(String filename)throws IOException{        FileInputStream in=new FileInputStream(filename);        byte[] buf=new byte[20*1024];        //從in中批量讀取位元組,放入到buf這個位元組數組中,從第0個位置開始放,        //最多放buf.length個 返回的是讀到的位元組的個數        /*        int bytes=in.read(buf,0, buf.length);//一次性讀完,說明位元組數組足夠大        int j=1;        for(int i=0;i<bytes;i++){            if((buf[i]&0xff)>0&&(buf[i]&0xff)<=0xf){                System.out.print("0");            }            System.out.print(Integer.toHexString(buf[i])+" ");            if(j++%10==0)                System.out.println();        }*/        //迴圈利用buf數組,防止開闢數組空間不夠用情況        int bytes=0;        int j=1;        while((bytes=in.read(buf,0,buf.length))!=-1){            for(int i=0;i<bytes;i++) {                //為了避免資料類型轉換錯誤,將高24位清零                System.out.print(Integer.toHexString(buf[i] & 0xff) + " ");                if(j++%10==0)                    System.out.println();            }        }    }

檔案的複製
//如果檔案不存在直接建立,如果存在,刪除後建立。 如果append=true,不存在的時候則追加
FileOutputStream out=new FileOutputStream("demo/out.dat");

   public static void copyFile(File srcFile,File destFile)throws IOException{        if(!srcFile.exists())            throw new IllegalArgumentException("檔案"+srcFile+"不存在");        if(!srcFile.isFile())            throw new IllegalArgumentException(srcFile+"不是檔案");        FileInputStream in=new FileInputStream(srcFile);        FileOutputStream out=new FileOutputStream(destFile);        byte[] buf=new byte[8*1024];        int b;        while((b=in.read(buf,0,buf.length))!=-1){            out.write(buf,0,b);            out.flush();//最好加上        }        in.close();        out.close();    }
    //利用帶緩衝的位元組流    public static void copytFileByBuffer(File srcFile,File destFile)throws IOException{        if(!srcFile.exists())            throw new IllegalArgumentException("檔案"+srcFile+"不存在");        if(!srcFile.isFile())            throw new IllegalArgumentException(srcFile+"不是檔案");        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile));        int c;        while((c=bis.read())!=-1){            bos.write(c);            bos.flush();//重新整理緩衝區        }        bis.close();        bos.close();    }

2.字元流
1)編碼問題
2)認識文本和文字檔
java的文本 (char)是16位不帶正負號的整數,是字元的unicode編碼(雙位元組編碼)
檔案是byte byte byte...的資料序列
文字檔是文本(char)序列按照某種編碼方案(utf-8,utf-16be,gbk)序列化為byte的儲存結果
3)字元流 (reader writer)---> 操作的是文字檔
字元的處理 一次處理一個字元
字元的底層仍然是基本的位元組序列
字元流的基本實現
InputStreamReader 完成byte流解析為char流,按照編碼解析
OutputStreamWriter 提供char流到byte流,按照編碼處理

//注意編碼問題public class IsrAndOswDemo {    public static void main(String[] args) throws IOException {        FileInputStream in=new FileInputStream("G:\\11.txt");        InputStreamReader isr=new InputStreamReader(in,"utf-8");//預設項目的編碼        FileOutputStream out=new FileOutputStream("G:\\12.txt");        OutputStreamWriter osw=new OutputStreamWriter(out,"utf-8");//        int c;//        while((c=isr.read())!=-1){//            System.out.print((char)c);//        }        char[] buffer=new char[8*1024];        int c;        while((c=isr.read(buffer,0,buffer.length))!=-1){            String s=new String(buffer,0,c);            System.out.println(s);            osw.write(buffer,0,c);            osw.flush();        }        isr.close();        osw.close();    }}

FileReader/FileWriter

public class FrAndFwDemo {    public static void main(String[] args) throws IOException {        FileReader fr=new FileReader("g:\\11.txt");        FileWriter fw=new FileWriter("g:\\13.txt");        char[] buffer=new char[2056];        int c;        while((c=fr.read(buffer,0,buffer.length))!=-1){            fw.write(buffer,0,c);            fw.flush();        }        fr.close();        fw.close();    }}

字元流的過濾器
BufferedReader ---> readLine 一次讀一行
BufferedWriter/PrintWriter --->寫一行

public class BrAndBwOrPwDemo {    public static void main(String[] args) throws IOException{        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("g:\\11.txt")));       // BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("g:\\123.txt")));        PrintWriter pw=new PrintWriter("g:\\1234.txt");        String line;        while((line=br.readLine())!=null){            System.out.println(line);            pw.println(line);            pw.flush();//            bw.write(line);//            //單獨寫出換行操作//            bw.newLine();//換行操作//            bw.flush();        }        pw.close();        br.close();//        bw.close();    }}

歡迎加入學習交流群569772982,大家一起學習交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.