文件和流

IO作用:解決設(shè)備和設(shè)備之間數(shù)據(jù)傳輸問題,內(nèi)存->硬盤,硬盤->內(nèi)存,鍵盤數(shù)據(jù)->內(nèi)存數(shù)據(jù)存到硬盤上,就做到了永久保存,數(shù)據(jù)一般是以文件形式保存到硬盤上,sun用File描述文件文件夾

File構(gòu)造方法

File file = new File(String pathname);

public class Test {
    public static void main(String[] args) {
        File file = new File("E:\\test.txt");
        try {
            file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

在文件夾里創(chuàng)建文件
File file = new File (String 文件夾, String 文件名);

public class Test {
    public static void main(String[] args) {
        File file = new File("E:\\k","test.txt");
        try {
            file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

在文件夾中的文件夾里創(chuàng)建文件

public class Test {
    public static void main(String[] args) {
        File file1 = new File("E:\\k\\k")
        File file = new File(file1,"test.txt");
        try {
            file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

絕對(duì)路徑 & 相對(duì)路徑

相對(duì)路徑不能跨盤
相對(duì)路徑:../../Test1.txt, ./Test1.txt = Test1.txt

創(chuàng)建

創(chuàng)建文件:
createNewFile();
創(chuàng)建單層文件夾:
mkdir();

//在E盤里創(chuàng)建一個(gè)叫k的文件夾
File file = new File("E:/k");
try{
  file.mkdir();
}catch(Exception e){
  e.printStackTrace();
}

mkdir
public boolean mkdir()
創(chuàng)建此抽象路徑名指定的目錄。
返回:
當(dāng)且僅當(dāng)已創(chuàng)建目錄時(shí),返回 true;否則返回 false

File file = new File("E:.k.txt");
boolean b = file.mkdir();
System.out.println(b);

創(chuàng)建多層文件夾:
mkdirs();

File file = new File("E:/a/b/c/d");
file.mkdirs();

文件重命名:

File srcFile = new File("E:/test.txt");
File destFile = new File("E:/k.txt");
srcFile.renameTo(destFile);

刪除文件(夾):

File srcFile = new File("E:/test.txt");
File destFile = new File("E:/k.txt");
srcFile.delete();

刪除成功返回true,否則返回false

存在:
exists();
System.out.println(srcFile.exists());
boolean型, 存在返回true,否則返回false

是不是文件: src.isFile(); boolean型

是不是目錄:isDirectory(); boolean

是不是一個(gè)目錄: isDirectory(); boolean

是否被隱藏: isHidden(); boolean

是否是絕對(duì)路徑: isAbsolute(); boolean

獲取文件名: getName(); String

獲取(假)絕對(duì)路徑: getPath(); String

獲取絕對(duì)路徑: getAbsolutePath(); String

獲取文件內(nèi)容字節(jié)個(gè)數(shù): long length();

獲取最后一次修改時(shí)間: lastModified();

獲取次抽象路徑名表示的目錄中的所有子文件(夾):
File[] listFiles(); 數(shù)組

File file = new File("E:/k");
File[] list = file.listFiles();
for(File file1 : list){
  System.out.println(file1.getName());
}
//或取E盤k文件夾下的文件(夾)名
public class Test {
    public static void main(String[] args) {
        File file = new File("E:/k");
        test(file);
    }
    public static void test(File file){
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++){
            if (files[i].isFile()){
                System.out.println(files[i].getName());
            }else {
                test(files[i]);
            }
        }
    }
}
//獲取E盤k文件夾里所有文件名

獲取文件夾里的所有文件:
遞歸思想

public class Practice {
    public static void main(String[] args) {
       PrintFiles("e/neusoft");
    }
    public static void PrintFiles(String path){
        File file1 = new File(path);
        File[] files = file1.listFiles();
        for (File file : files){
            if (file.isFile()) {
                System.out.println(file.getName());
            }
            else if (file.isDirectory()){
                System.out.println(file.getAbsolutePath());
                PrintFiles(file.getAbsolutePath());
            }
        }
    }
}

流是指一連串流動(dòng)的字符,是以先進(jìn)先出方式發(fā)送信息的通道。
通過流來讀寫文件。
字符,字節(jié)流:

  • 往文本文檔里寫東西是字符流,字符輸入流Reader,字符輸出流Writer
  • 往word里寫東西是字節(jié)流,字節(jié)輸入流InputStream,字符輸出流OutputStream
    輸入,輸出流:
  • 往內(nèi)存里讀叫輸入流,InputStream 和Reader作為基類
  • 從內(nèi)存出叫輸出流,OutputStream和Writer作為基類

文本文件的讀寫:

  • 用FileInputStream和FileOutputStream讀寫
  • 用BufferedReader和BufferedWriter讀寫

二進(jìn)制文件讀寫:

  • 使用DataInputStream和DataOutputStream讀寫

使用FileInputStream讀寫:


image.png

InputStream類常用方法:
int read( ) 讀取一個(gè)字節(jié)
int read(byte[] b) 讀取一批字節(jié)
int read(byte[] b,int off,int len)
void close( )
子類FileInputStream常用的構(gòu)造方法
FileInputStream(File file)
FileInputStream(String name)

byte[] buffer = new byte[10];
buffer[0] = 97;
buffer[1]=98;//b
String string = new String(buffer,0//offset,2//length);
System.out.println(string);

read()

File file = new File("e:/test.txt");
System.out.println(file.length());
byte[] buffer = new byte[(int)file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
int index = 0;
byte content = (byte)fileInputStream.read();//讀取文件的一個(gè)字節(jié)
while (content != -1){
  buffer[index] = content;
  index++;
  content = (byte)fileInputStream.read();
}
System.out.println(Arrays.toString(buffer));
String string = new String(buffer,0,index);
System.out.println(string);

read(byte[] b)

public static void main(String[] args) throws IOException {
        // write your code here

        File file = new File("d:/我的青春誰做主.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] buffer = new byte[SIZE];//保存從磁盤讀到的字節(jié)


        int len = fileInputStream.read(buffer);//第一次讀文件中的100個(gè)字節(jié)
        while (len != -1)
        {
            String string = new String(buffer,0, len);
            System.out.println(string);
            //讀下一批字節(jié)
            len = fileInputStream.read(buffer);
        }
    }

寫文件:

FileOutputStream fileOutputStream = new FileOutputStream("e:/test.txt");
        String string = "good job";
        byte[] words = string.getBytes();
        fileOutputStream.write(words,0,words.length);

OutputStream類常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close( )
子類FileOutputStream常用的構(gòu)造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)
1、前兩種構(gòu)造方法在向文件寫數(shù)據(jù)時(shí)將覆蓋文件中原有的內(nèi)容
2、創(chuàng)建FileOutputStream實(shí)例時(shí),如果相應(yīng)的文件并不存在,則會(huì)自動(dòng)創(chuàng)建一個(gè)空的文件

復(fù)制文件內(nèi)容
文件“我的青春誰做主.txt”位于D盤根目錄下,要求將此文件的內(nèi)容復(fù)制到
C:\myFile\my Prime.txt中
實(shí)現(xiàn)思路:
創(chuàng)建文件“D:\我的青春誰做主.txt”并自行輸入內(nèi)容
創(chuàng)建C:\myFile的目錄。
創(chuàng)建輸入流FileInputStream對(duì)象,負(fù)責(zé)對(duì)D:\我的青春誰做主.txt文件的讀取。
創(chuàng)建輸出流FileOutputStream對(duì)象,負(fù)責(zé)將文件內(nèi)容寫入到C:\myFile\my Prime.txt中。
創(chuàng)建中轉(zhuǎn)站數(shù)組words,存放每次讀取的內(nèi)容。
通過循環(huán)實(shí)現(xiàn)文件讀寫。
關(guān)閉輸入流、輸出流

 File file = new File("e:/Test.txt");
        File file1 = new File("d:/myFile");
        try{
            file1.mkdir();
        }catch (Exception e){
            e.printStackTrace();
        }
        File file2 = new File("d:/myFile/my Prime.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileOutputStream fileOutputStream = new FileOutputStream(file2);
        byte[] buffer = new byte[5];
        int read_len = fileInputStream.read(buffer);
        while (read_len != -1){
            String string = new String(buffer,0,read_len);
            System.out.println(string);
            byte[] words = string.getBytes();
            fileOutputStream.write(words,0,words.length);
            read_len = fileInputStream.read(buffer);
        }
File file = new File("e:/c2fdfc039245d688c56332adacc27d1ed21b2451.jpg");
        File file1 = new File("d:/myFile");
        if (!file1.exists()){
            file1.mkdir();
        }
        File file2 = new File("d:/myFile/my Prime.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileOutputStream fileOutputStream = new FileOutputStream(file2);
        byte[] buffer = new byte[10];
        int read_len = fileInputStream.read(buffer);
        while (read_len != -1){
            fileOutputStream.write(buffer,0,buffer.length);
            read_len = fileInputStream.read(buffer);
        }
        fileInputStream.close();
        fileOutputStream.close();

使用字符流讀寫文件

使用FileReader讀取文件

public static void main(String[] args) throws IOException {
        //
        FileReader fileReader = new FileReader("D:/我的青春誰做主.txt");

        char[] array = new char[100];
        int length = fileReader.read(array);
        StringBuilder sb = new StringBuilder();//拼接字符串
        while (length != -1)
        {
            sb.append(array);//追加字符串
            length = fileReader.read(array);
        }

        System.out.println(sb.toString());
        fileReader.close();

    }
FileReader fileReader = new FileReader("e:/test.txt");
        char[] chars = new char[5];
        int length = fileReader.read(chars);
        StringBuilder stringBuilder = new StringBuilder();
        int count = 0;
        while (length != -1){
            count++;
            System.out.println(count);
            stringBuilder.append(chars);
            Arrays.fill(chars,'\u0000');
            length = fileReader.read(chars);
            
        }
        System.out.println(stringBuilder.toString());
        fileReader.close();

BufferedReader類

使用FileReader類與BufferedReader類
BufferedReader類是Reader類的子類
BufferedReader類帶有緩沖區(qū)
按行讀取內(nèi)容的readLine()方法


image.png
public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("D:/我的青春誰做主.txt");

        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String strContent = bufferedReader.readLine();
        StringBuilder sb = new StringBuilder();
        while (strContent != null)
        {
            sb.append(strContent);
            sb.append("\n");
            sb.append("\r");
            strContent = bufferedReader.readLine();
        }

        System.out.println(sb.toString());
        fileReader.close();
        bufferedReader.close();
    }

使用FileWriter寫文件

FileWriter fileWriter = new FileWriter("e:/test.txt");
fileWriter.append("hello world");
fileWriter.flush();
fileWriter.close();

如何提高字符流寫文本文件的效率?
使用FileWriter類與BufferedWriter類
BufferedWriter類是Writer類的子類
BufferedWriter類帶有緩沖區(qū)


image.png
public class BufferedWriterTest {
    public static void main(String[] args) {
        FileWriter fw=null;
        BufferedWriter bw=null;
        FileReader fr=null;
        BufferedReader br=null;
        try {
           //創(chuàng)建一個(gè)FileWriter 對(duì)象
           fw=new FileWriter("D:\\myDoc\\hello.txt"); 
           //創(chuàng)建一個(gè)BufferedWriter 對(duì)象
           bw=new BufferedWriter(fw); 
           bw.write("大家好!"); 
           bw.write("我正在學(xué)習(xí)BufferedWriter。"); 
           bw.newLine(); 
           bw.write("請(qǐng)多多指教!"); 
           bw.newLine();               
           bw.flush();
                       
           //讀取文件內(nèi)容
            fr=new FileReader("D:\\myDoc\\hello.txt"); 
            br=new BufferedReader(fr); 
            String line=br.readLine();
            while(line!=null){ 
                System.out.println(line);
                line=br.readLine(); 
            }
          
            fr.close(); 
           }catch(IOException e){
                System.out.println("文件不存在!");
           }finally{
               try{
                   if(fw!=null)
                       fw.close();
                   if(br!=null)
                       br.close();
                   if(fr!=null)
                       fr.close();  
               }catch(IOException ex){
                    ex.printStackTrace();
               }
           }
    }
}

文本拷貝

FileReader fr = new FileReader("e:/test.txt");
        FileWriter wr = new FileWriter("d:/myFile/my Prime.txt");
        BufferedReader reader = new BufferedReader(fr);
        BufferedWriter writer = new BufferedWriter(wr);
        StringBuffer str = new StringBuffer();
        String line = reader.readLine();
        while (line != null){
            str.append(line);
            str.append("\n");
            str.append("\t");
            wr.flush();
            line = reader.readLine();
        }
        System.out.println(str.toString());
        String string = str.toString().replace("{name}","golden");
        string = string.toString().replace("{type}","dog");
        string = string.toString().replace("{master}","zabrath");
        System.out.println(string);
        writer.write(string);
        writer.flush();

練習(xí) 統(tǒng)計(jì)某個(gè)文件夾下所有java文件代碼行數(shù)之和:

File file = new File("C:\\Users\\Administrator\\IdeaProjects\\jemalsjava\\src\\com\\company\\");
        File[] arr = file.listFiles();
        int totalCount = 0;
        for (File file1 : arr){
            FileReader fileReader = new FileReader(file1);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            int countLine = 0;
            String strLine = bufferedReader.readLine();
            while (strLine != null){
                countLine++;
                strLine = bufferedReader.readLine();
            }
            totalCount += countLine;
        }
        System.out.println(totalCount);
package com.company;

import java.io.*;

/**
 * Created by ttc on 2018/6/5.
 */
public class CodeLinesCount {
    public static int CountLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        int count = 0;
        String strLine = bufferedReader.readLine();
        while(strLine != null)
        {
            count++;
            strLine = bufferedReader.readLine();
        }
        System.out.println(count);
        return count;
    }
    public static void main(String[] args) throws IOException {
//        CountLines("d:/Main.java");
        File file = new File("D:\\javacode");
        File[] files = file.listFiles();
        int sum = 0;
        for(File file1 : files)
        {
            System.out.println(file1.getPath());
            int count = CountLines(file1.getPath());
            sum += count;
        }
        System.out.println(sum);
    }
}

DataOutputStream和DataInputStream

DataOutputStream數(shù)據(jù)輸出流: 將java基本數(shù)據(jù)類型寫入數(shù)據(jù)輸出流中。
DataInputStream數(shù)據(jù)輸入流:將DataOutputStream寫入流中的數(shù)據(jù)讀入。

DataOutputStream中write的方法重載:

繼承了字節(jié)流父類的兩個(gè)方法:
(1)void write(byte[] b,int off,int len);
(2)void write(int b);//寫入U(xiǎn)TF數(shù)值,代表字符
注意字節(jié)流基類不能直接寫入string 需要先將String轉(zhuǎn)化為getByte()轉(zhuǎn)化為byte數(shù)組寫入
特有的指定基本數(shù)據(jù)類型寫入:
(1)void writeBoolean(boolean b);//將一個(gè)boolean值以1byte形式寫入基本輸出流。
(2)void writeByte(int v);//將一個(gè)byte值以1byte值形式寫入到基本輸出流中。
(3)void writeBytes(String s);//將字符串按字節(jié)順序?qū)懭氲交据敵隽髦小?br> (4)void writeChar(int v);//將一個(gè)char值以2byte形式寫入到基本輸出流中。先寫入高字節(jié)。寫入的也是編碼值;
(5)void writeInt(int v);//將一個(gè)int值以4byte值形式寫入到輸出流中先寫高字節(jié)。
(6)void writeUTF(String str);//以機(jī)器無關(guān)的的方式用UTF-8修改版將一個(gè)字符串寫到基本輸出流。該方法先用writeShort寫入兩個(gè)字節(jié)表示后面的字節(jié)數(shù)。

DataInputStream中read方法重載:

繼承了字節(jié)流父類的方法:
int read();
int read(byte[] b);
int read(byte[] buf,int off,int len);
對(duì)應(yīng)write方法的基本數(shù)據(jù)類型的讀出:
String readUTF();//讀入一個(gè)已使用UTF-8修改版格式編碼的字符串
boolean readBoolean;
int readInt();
byte readByte();
char readChar();
注意:
基本數(shù)據(jù)類型的寫入流和輸出流,必須保證以什么順序按什么方式寫入數(shù)據(jù),就要按什么順序什么方法讀出數(shù)據(jù),否則會(huì)導(dǎo)致亂碼,或者異常產(chǎn)生。

public class DataStream {
    public static void main(String[] args) throws IOException {
        String[] strings = {"main","flush","String","FileOutputStream","java.io.*"};
        FileOutputStream fileOutputStream = new FileOutputStream("e:/output.txt");
        DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

        for(String string : strings)
        {
            int strlen = string.length();
            dataOutputStream.writeShort(strlen);
            dataOutputStream.writeBytes(string);
        }


        dataOutputStream.flush();
        dataOutputStream.close();

        FileInputStream fileInputStream = new FileInputStream("e:/output.txt");
        DataInputStream dataInputStream = new DataInputStream(fileInputStream);

        while(true)
        {
            try {
                short len = dataInputStream.readShort();
                byte[] bytes = new byte[len];
                dataInputStream.read(bytes);
                String string = new String(bytes,0,bytes.length);
                System.out.println(string);
            }
            catch (EOFException ex)
            {
                break;
            }

        }

    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,533評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,055評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,365評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,561評(píng)論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,346評(píng)論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,889評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,978評(píng)論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,118評(píng)論 0 286
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,637評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,558評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,739評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,246評(píng)論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 43,980評(píng)論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,619評(píng)論 1 280
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,347評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,702評(píng)論 2 370

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