java文件操作總結(jié)

RandomAccessFile 相關(guān)API的使用

    pointer=0; 文件指針
        寫方法 raf.write(int) -->只寫一個字節(jié) 后8位候衍,同時指針指向下一個位置,準(zhǔn)備再次寫入
        讀方法 int b = raf.read()-->讀一個字節(jié)
        讀寫文件完成后一定要關(guān)閉
    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');//只寫了一個字節(jié)
        System.out.println(raf.getFilePointer());
        raf.write('B');
        int i=0x7fffffff;
        //用write方法 每次只能寫一個字節(jié)蛇捌,如果要把i寫進(jìn)去就得寫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);//寫入字節(jié)數(shù)組
        System.out.println(raf.length());
        //讀文件必須把指針移到頭部
        raf.seek(0);
        //一次性讀取毕贼。把文件中內(nèi)容讀取到字節(jié)數(shù)組中
        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流(輸入流拄衰,輸出流)
字節(jié)流卫漫,字符流
1.字節(jié)流
1)InputStream、OutputStream
InputStream抽象了應(yīng)用程序讀取數(shù)據(jù)的方式
OutputStream抽象了應(yīng)用程序?qū)懗鰯?shù)據(jù)的方式
2)EOF=End 讀到-1就讀到結(jié)尾
3)輸入流基本方法
int b=in.read(); 讀取一個字節(jié)無符號填充到int的低八位肾砂。-1是EOF
in.read(byte[] buf)讀取數(shù)據(jù)填充到字節(jié)數(shù)組buf
in.read(byte[] buf,int start,int size)讀取數(shù)據(jù)填充到字節(jié)數(shù)組buf列赎,從buf的start位置開始,存放size長度的數(shù)據(jù)
4)輸出流基本方法
out.write(int b)寫出一個byte到流镐确,b的低8位
out.write(byte[] buf)將buf字節(jié)數(shù)組都寫入到流
out.write(byte[] buf,int start,int size)
5)FileInputStream--->具體實(shí)現(xiàn)了在文件上讀取數(shù)據(jù)
6)FileOutputStream 實(shí)現(xiàn)了向文件中寫出byte數(shù)據(jù)的方法
7)DataOutputStream/DataInputStream
對流功能的擴(kuò)展包吝,可以更加方便的讀取Int,long,字符等類型數(shù)據(jù)
DataOutputStream
writeInt()/writeDouble()/writeUTF()
DataOutputStream dos=new DataOutputStream(new FileOutputStream(file));
8)BufferedInputStream&BufferedOutputStream
這兩個流類為IO提供了帶緩沖區(qū)的操作,一般打開文件進(jìn)行寫入或讀取操作時源葫,都會加上緩沖诗越,這種流模式提高了IO的性能

從應(yīng)用程序中把輸入放入文件,相當(dāng)于將一缸水倒入到另一個缸中:
FileOutputStream--->write方法黨羽與一滴一滴把水轉(zhuǎn)移過去
DataOutputStream--->writexxx()方法會方便一些息堂,相當(dāng)于一瓢一瓢轉(zhuǎn)移
BufferedOutputStream--->write方法更方便嚷狞,相當(dāng)于一瓢一瓢水先放入桶中,再從桶中導(dǎo)入到另一個缸中

使用in.read()方法

    /*
    讀取指定文件內(nèi)容荣堰,按照16進(jìn)制輸出到控制臺
    并且每輸出10個byte換行
     */
    public static void printHex(String filename) throws IOException {
        //把文件作為字節(jié)流進(jìn)行讀操作
        FileInputStream in=new FileInputStream(filename);
        int b;
        int i=1;
        while((b=in.read())!=-1){
            if(b<=0xf) {
                //單位數(shù)前面補(bǔ)0
                System.out.print("0");
            }
            System.out.print(Integer.toHexString(b)+" ");//將整形b轉(zhuǎn)換為16進(jìn)制的字符串
            if(i++%10==0)
                System.out.println();
        }
        in.close();
    }

使用in.read(byte[] buf , int start , int size)
將數(shù)據(jù)讀取到字節(jié)數(shù)組中床未,返回?cái)?shù)據(jù)大小,循環(huán)輸出字節(jié)數(shù)組

 public static void printHexByByteArray(String filename)throws IOException{
        FileInputStream in=new FileInputStream(filename);
        byte[] buf=new byte[20*1024];
        //從in中批量讀取字節(jié)振坚,放入到buf這個字節(jié)數(shù)組中薇搁,從第0個位置開始放,
        //最多放buf.length個 返回的是讀到的字節(jié)的個數(shù)
        /*
        int bytes=in.read(buf,0, buf.length);//一次性讀完渡八,說明字節(jié)數(shù)組足夠大
        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();
        }*/

        //循環(huán)利用buf數(shù)組啃洋,防止開辟數(shù)組空間不夠用情況
        int bytes=0;
        int j=1;
        while((bytes=in.read(buf,0,buf.length))!=-1){
            for(int i=0;i<bytes;i++) {
                //為了避免數(shù)據(jù)類型轉(zhuǎn)換錯誤传货,將高24位清零
                System.out.print(Integer.toHexString(buf[i] & 0xff) + " ");
                if(j++%10==0)
                    System.out.println();
            }
        }
    }

文件的復(fù)制
//如果文件不存在直接創(chuàng)建,如果存在宏娄,刪除后創(chuàng)建问裕。 如果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();
    }
    //利用帶緩沖的字節(jié)流
    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();//刷新緩沖區(qū)
        }
        bis.close();
        bos.close();
    }

2.字符流
1)編碼問題
2)認(rèn)識文本和文本文件
java的文本 (char)是16位無符號整數(shù)孵坚,是字符的unicode編碼(雙字節(jié)編碼)
文件是byte byte byte...的數(shù)據(jù)序列
文本文件是文本(char)序列按照某種編碼方案(utf-8,utf-16be,gbk)序列化為byte的存儲結(jié)果
3)字符流 (reader writer)---> 操作的是文本文件
字符的處理 一次處理一個字符
字符的底層仍然是基本的字節(jié)序列
字符流的基本實(shí)現(xiàn)
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");//默認(rèn)項(xiàng)目的編碼
        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);
//            //單獨(dú)寫出換行操作
//            bw.newLine();//換行操作
//            bw.flush();
        }
        pw.close();
        br.close();
//        bw.close();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末十饥,一起剝皮案震驚了整個濱河市窟勃,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌逗堵,老刑警劉巖秉氧,帶你破解...
    沈念sama閱讀 211,194評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異蜒秤,居然都是意外死亡汁咏,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,058評論 2 385
  • 文/潘曉璐 我一進(jìn)店門作媚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來攘滩,“玉大人,你說我怎么就攤上這事纸泡∑剩” “怎么了?”我有些...
    開封第一講書人閱讀 156,780評論 0 346
  • 文/不壞的土叔 我叫張陵女揭,是天一觀的道長蚤假。 經(jīng)常有香客問我,道長吧兔,這世上最難降的妖魔是什么磷仰? 我笑而不...
    開封第一講書人閱讀 56,388評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮境蔼,結(jié)果婚禮上灶平,老公的妹妹穿的比我還像新娘。我一直安慰自己箍土,他們只是感情好逢享,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,430評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著涮帘,像睡著了一般拼苍。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上调缨,一...
    開封第一講書人閱讀 49,764評論 1 290
  • 那天疮鲫,我揣著相機(jī)與錄音,去河邊找鬼弦叶。 笑死俊犯,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的伤哺。 我是一名探鬼主播燕侠,決...
    沈念sama閱讀 38,907評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼立莉!你這毒婦竟也來了绢彤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,679評論 0 266
  • 序言:老撾萬榮一對情侶失蹤蜓耻,失蹤者是張志新(化名)和其女友劉穎茫舶,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體刹淌,經(jīng)...
    沈念sama閱讀 44,122評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡饶氏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,459評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了有勾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片疹启。...
    茶點(diǎn)故事閱讀 38,605評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖蔼卡,靈堂內(nèi)的尸體忽然破棺而出荤懂,到底是詐尸還是另有隱情谣蠢,我是刑警寧澤挤忙,帶...
    沈念sama閱讀 34,270評論 4 329
  • 正文 年R本政府宣布赏僧,位于F島的核電站挽绩,受9級特大地震影響肩民,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,867評論 3 312
  • 文/蒙蒙 一剿涮、第九天 我趴在偏房一處隱蔽的房頂上張望怀吻。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,734評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽棋电。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背闷叉。 一陣腳步聲響...
    開封第一講書人閱讀 31,961評論 1 265
  • 我被黑心中介騙來泰國打工擦俐, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人握侧。 一個月前我還...
    沈念sama閱讀 46,297評論 2 360
  • 正文 我出身青樓蚯瞧,卻偏偏與公主長得像,于是被迫代替她去往敵國和親藕咏。 傳聞我的和親對象是個殘疾皇子状知,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,472評論 2 348

推薦閱讀更多精彩內(nèi)容