16 文件與流

什么是文件恒序?

文件可認(rèn)為是相關(guān)記錄或放在一起的數(shù)據(jù)的集合

文件一般存儲(chǔ)在哪里啦撮?

image.png

JAVA程序如何訪問文件屬性顾稀?

java.io.File 類

File類訪問文件屬性

image.png

JAVA中的文件及目錄處理類

在Java中提供了操作文件及目錄(即我們所說的文件夾)類File。有以下幾點(diǎn)注意事項(xiàng):

(1)不論是文件還是目錄都使用File類操作;

(2)File類只提供操作文件及目錄的方法痒芝,并不能訪問文件的內(nèi)容俐筋,所以他描述的是文件本身的屬性;

(3)如果要訪問文件本身,用到了我們下面要學(xué)習(xí)的IO流.

一:構(gòu)造方法

File 文件名/目錄名 = new File("文字路徑字符串");

在Java中提供了幾種創(chuàng)建文件及目錄的構(gòu)造方法严衬,但大體上都是用參數(shù)中的文字路徑字符串來創(chuàng)建澄者。

二:一般方法

(1)文件檢測(cè)相關(guān)方法

boolean isDirectory():判斷File對(duì)象是不是目錄

boolean isFile():判斷File對(duì)象是不是文件

boolean exists():判斷File對(duì)象對(duì)應(yīng)的文件或目錄是不是存在

(2)文件操作的相關(guān)方法

boolean createNewFile():路徑名指定的文件不存在時(shí),創(chuàng)建一個(gè)新的空文件

boolean delete():刪除File對(duì)象對(duì)應(yīng)的文件或目錄

(3)目錄操作的相關(guān)方法

boolean mkdir():?jiǎn)螌觿?chuàng)建空文件夾

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

File[] listFiles():返回File對(duì)象表示的路徑下的所有文件對(duì)象數(shù)組

(4)訪問文件相關(guān)方法

String getName():獲得文件或目錄的名字

String getAbsolutePath():獲得文件目錄的絕對(duì)路徑

String getParent():獲得對(duì)象對(duì)應(yīng)的目錄的父級(jí)目錄

long lastModified():獲得文件或目錄的最后修改時(shí)間

long length() :獲得文件內(nèi)容的長(zhǎng)度

目錄的創(chuàng)建

public class MyFile {
  public static void main(String[] args) {
      //創(chuàng)建一個(gè)目錄
      File file1 = new File("d:\\test");
      //判斷對(duì)象是不是目錄
      System.out.println("是目錄嗎瞳步?"+file1.isDirectory());
      //判斷對(duì)象是不是文件
      System.out.println("是文件嗎闷哆?"+file1.isFile());
      //獲得目錄名
      System.out.println("名稱:"+file1.getName());
      //獲得相對(duì)路徑
      System.out.println("相對(duì)路徑:"+file1.getPath());
      //獲得絕對(duì)路徑
      System.out.println("絕對(duì)路徑:"+file1.getAbsolutePath());
      //最后修改時(shí)間
      System.out.println("修改時(shí)間:"+file1.lastModified());
      //文件大小
      System.out.println("文件大小:"+file1.length());
  }
}

程序首次運(yùn)行結(jié)果:

是目錄嗎单起?false
是文件嗎抱怔?false
名稱:test
相對(duì)路徑:d:\test
絕對(duì)路徑:d:\test
修改時(shí)間:0
文件大小:0

file1對(duì)象是目錄啊嘀倒,怎么在判斷“是不是目錄”時(shí)輸出了false呢屈留?這是因?yàn)橹皇莿?chuàng)建了代表他是目錄的對(duì)象局冰,還沒有真正的創(chuàng)建,這時(shí)候要用到mkdirs()方法灌危,如下:

public class MyFile {
    public static void main(String[] args) {
        //創(chuàng)建一個(gè)目錄
        File file1 = new File("d:\\test\\test");
        file1.mkdirs();//創(chuàng)建了多級(jí)目錄
        //判斷對(duì)象是不是目錄
        System.out.println("是目錄嗎康二?"+file1.isDirectory());     
    }
}

文件的創(chuàng)建

public class MyFile {
    public static void main(String[] args) {
        //創(chuàng)建一個(gè)文件
        File file1 = new File("d:\\a.txt");
                                                                                                                                                                                                                                                                
        //判斷對(duì)象是不是文件
        System.out.println("是文件嗎?"+file1.isFile());  
    }
}

首次運(yùn)行結(jié)果:

是文件嗎勇蝙?false

同樣會(huì)發(fā)現(xiàn)類似于上面的問題沫勿,這是因?yàn)橹皇谴砹艘粋€(gè)文件對(duì)象,并沒有真正的創(chuàng)建味混,要用到createNewFile()方法产雹,如下

public class MyFile {
    public static void main(String[] args) {
        //創(chuàng)建一個(gè)文件對(duì)象
        File file1 = new File("d:\\a.txt");
        try {
            file1.createNewFile();//創(chuàng)建真正的文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判斷對(duì)象是不是文件
        System.out.println("是文件嗎?"+file1.isFile());  
    }
}

文件夾與文件的創(chuàng)建目錄

文件時(shí)存放在文件夾下的翁锡,所以應(yīng)該先創(chuàng)建文件夾蔓挖,后創(chuàng)建文件,如下:

public class MyFile {
    public static void main(String[] args) {
        //代表一個(gè)文件夾對(duì)象,單層的創(chuàng)建
        File f3 = new File("d:/test");
        File f4 = new File("d:/test/a.txt");
        f3.mkdir();//先創(chuàng)建文件夾馆衔,才能在文件夾下創(chuàng)建文件
        try {
            f4.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
                                                                                                                                                                   
        //代表一個(gè)文件夾對(duì)象,多層的創(chuàng)建
        File f5= new File("d:/test/test/test");
        File f6 = new File("d:/test/test/test/a.txt");
        f5.mkdirs();//多層創(chuàng)建
        try {
            f6.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

運(yùn)行結(jié)果為瘟判,在D磁盤的test文件夾下有一個(gè)a.txt,在D磁盤的test/test/test下有一個(gè)a.txt文件角溃。

編程:判斷是不是有這個(gè)文件拷获,若有則刪除,沒有則創(chuàng)建

public class TestFileCreatAndDele {
    public static void main(String[] args) {
        File f1 = new File("d:/a.txt");
        if(f1.exists()){//文件在嗎
            f1.delete();//在就刪除
        }else{//不在
            try {
                f1.createNewFile();//就重新創(chuàng)建
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

文件的逐層讀取

File的listFiles()只能列出當(dāng)前文件夾下的文件及目錄开镣,那么其子目錄下的文件及目錄該如何獲取呢刀诬?解決的辦法有很多,在這運(yùn)用遞歸解決.

//逐層獲取文件及目錄
public class TestFindFile {
    public static void openAll(File f) {// 遞歸的實(shí)現(xiàn)
        File[] arr = f.listFiles();// 先列出當(dāng)前文件夾下的文件及目錄
        for (File ff : arr) {
            if (ff.isDirectory()) {// 列出的東西是目錄嗎
                System.out.println(ff.getName());
                openAll(ff);// 是就繼續(xù)獲得子文件夾邪财,執(zhí)行操作
            } else {
                // 不是就把文件名輸出
                System.out.println(ff.getName());
            }
        }
    }
    public static void main(String[] args) {
        File file = new File("d:/test");// 創(chuàng)建目錄對(duì)象
        openAll(file);// 打開目錄下的所有文件及文件夾
    }
}

如何讀寫文件陕壹?
通過流來讀寫文件
流是指一連串流動(dòng)的字符,是以先進(jìn)先出方式發(fā)送信息的通道

image.png

輸入/輸出流與數(shù)據(jù)源

image.png

Java流的分類

image.png

文本文件的讀寫

  • 用FileInputStream和FileOutputStream讀寫文本文件
  • 用BufferedReader和BufferedWriter讀寫文本文件

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

  • 使用DataInputStream和DataOutputStream讀寫二進(jìn)制文件

使用FileInputStream 讀文本文件

image.png

InputStream類常用方法
int read( )
int read(byte[] b)
int read(byte[] b,int off,int len)
void close( )
子類FileInputStream常用的構(gòu)造方法
FileInputStream(File file)
FileInputStream(String name)

一個(gè)一個(gè)字節(jié)的讀

 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[100];//保存從磁盤讀到的字節(jié)
        int index = 0;

        int content = fileInputStream.read();//讀文件中的一個(gè)字節(jié)

        while (content != -1)//文件中還有內(nèi)容,沒有讀完
        {
            buffer[index] = (byte)content;
            index++;

            //讀文件中的下一個(gè)字節(jié)
            content = fileInputStream.read();
        }

        //此時(shí)buffer數(shù)組中讀到了文件的所有字節(jié)

        String string = new String(buffer,0, index);

        System.out.println(string);

    }


一批一批的讀

  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 寫文本文件

image.png
public class FileOutputStreamTest {
    
    public static void main(String[] args) {
        FileOutputStream fos=null;
         try {
             String str ="好好學(xué)習(xí)Java";
             byte[] words  = str.getBytes();
             fos = new FileOutputStream("D:\\myDoc\\hello.txt");
             fos.write(words, 0, words.length);
             System.out.println("hello文件已更新!");
          }catch (IOException obj) {
              System.out.println("創(chuàng)建文件時(shí)出錯(cuò)!");
          }finally{
              try{
                  if(fos!=null)
                      fos.close();
              }catch (IOException e) {
                 e.printStackTrace();
              }
          }
    }
}

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)思路

  1. 創(chuàng)建文件“D:\我的青春誰做主.txt”并自行輸入內(nèi)容
  2. 創(chuàng)建C:\myFile的目錄。
  3. 創(chuàng)建輸入流FileInputStream對(duì)象绊袋,負(fù)責(zé)對(duì)D:\我的青春誰做主.txt文件的讀取毕匀。
  4. 創(chuàng)建輸出流FileOutputStream對(duì)象,負(fù)責(zé)將文件內(nèi)容寫入到C:\myFile\my Prime.txt中癌别。
  5. 創(chuàng)建中轉(zhuǎn)站數(shù)組words皂岔,存放每次讀取的內(nèi)容。
  6. 通過循環(huán)實(shí)現(xiàn)文件讀寫展姐。
  7. 關(guān)閉輸入流躁垛、輸出流
  public static void main(String[] args) throws IOException {
        //創(chuàng)建E:\myFile的目錄剖毯。

        File folder = new File("E:\\myFile");
        if (!folder.exists())//判斷目錄是否存在
        {
            folder.mkdirs();//如果不存在,創(chuàng)建該目錄
        }

        //創(chuàng)建輸入流
        File fileInput = new File("d:/b.rar");
        FileInputStream fileInputStream = new FileInputStream(fileInput);
        //創(chuàng)建輸出流
        FileOutputStream fileOutputStream = new FileOutputStream("E:\\myFile\\c.rar");
        //創(chuàng)建中轉(zhuǎn)站數(shù)組buffer教馆,存放每次讀取的內(nèi)容
        byte[] buffer = new byte[1000];

        //從fileInputStream(d:/我的青春誰做主.txt)中讀100個(gè)字節(jié)到buffer中
        int length = fileInputStream.read(buffer);

        int count = 0;
        while (length != -1) //這次讀到了至少一個(gè)字節(jié)
        {
            System.out.println(length);
            //將buffer中內(nèi)容寫入到輸出流(E:\myFile\myPrime.txt)
            fileOutputStream.write(buffer,0,length);

            //繼續(xù)從輸入流中讀取下一批字節(jié)
            length = fileInputStream.read(buffer);
            count++;
        }
        System.out.println(count);

        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();

    }

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寫文件

public class WriterFiletTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Writer fw=null;
        try {
              //創(chuàng)建一個(gè)FileWriter對(duì)象
              fw=new FileWriter("D:\\myDoc\\簡(jiǎn)介.txt"); 
              //寫入信息
              fw.write("我熱愛我的團(tuán)隊(duì)!");            
              fw.flush();  //刷新緩沖區(qū)
             
        }catch(IOException e){
              System.out.println("文件不存在!");
        }finally{
            try {
                if(fw!=null)
                    fw.close();  //關(guān)閉流
             } catch (IOException e) {
                e.printStackTrace();
             }
        }
    }

}

如何提高字符流寫文本文件的效率土铺?
使用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();
               }
           }
    }
}

練習(xí)

格式模版保存在文本文件pet.template中镀钓,內(nèi)容如下:
您好!
我的名字是{name}镀迂,我是一只{type}。
我的主人是{master}唤蔗。
其中{name}探遵、{type}、{master}是需要替換的內(nèi)容妓柜,現(xiàn)在要求按照模板格式保存寵物數(shù)據(jù)到文本文件箱季,即把{name}、{type}棍掐、{master}替換為具體的寵物信息藏雏,該如何實(shí)現(xiàn)呢?

實(shí)現(xiàn)思路
1.創(chuàng)建字符輸入流BufferedReader對(duì)象
2.創(chuàng)建字符輸出流BufferedWriter對(duì)象

  1. 建StringBuffer對(duì)象sbf作煌,用來臨時(shí)存儲(chǔ)讀取的
    數(shù)據(jù)
  2. 通過循環(huán)實(shí)現(xiàn)文件讀取掘殴,并追加到sbf中
  3. 使用replace()方法替換sbf中的內(nèi)容
  4. 將替換后的內(nèi)容寫入到文件中
  5. 關(guān)閉輸入流、輸出流
public class ReaderAndWriterFile {

     public void replaceFile(String file1,String file2) {   
           BufferedReader reader = null;
           BufferedWriter writer = null;
         try {
            //創(chuàng)建 FileReader對(duì)象和FileWriter對(duì)象.
            FileReader fr  = new FileReader(file1);  
            FileWriter fw = new FileWriter(file2);
            //創(chuàng)建 輸入粟誓、輸入出流對(duì)象.
            reader = new BufferedReader(fr);
            writer = new BufferedWriter(fw);
            String line = null;
            StringBuffer sbf=new StringBuffer();  
            //循環(huán)讀取并追加字符
            while ((line = reader.readLine()) != null) {
                sbf.append(line);  
            }
            System.out.println("替換前:"+sbf);
            /*替換內(nèi)容*/
            String newString=sbf.toString().replace("{name}", "歐歐");
            newString = newString.replace("{type}", "狗狗");
            newString = newString.replace("{master}", "李偉");
            System.out.println("替換后:"+newString);
            writer.write(newString);  //寫入文件       
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //關(guān)閉 reader 和 writer.
            try {
                if(reader!=null)
                    reader.close();
                if(writer!=null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        ReaderAndWriterFile obj = new ReaderAndWriterFile();
        obj.replaceFile("c:\\pet.template", "D:\\myDoc\\pet.txt");          
    }
}

使用字符流讀寫文本更合適
使用字節(jié)流讀寫字節(jié)文件(音頻奏寨,視頻,圖片鹰服,壓縮文件等)更合適病瞳,文本文件也可以看成是有字節(jié)組成

圖片拷貝

public class move {  
    public static void main(String[] args)  
    {  
        String src="E:/DesktopFile/Android/CSDN.jpg";  
        String target="E:/DesktopFile/Android/test/CSDN.jpg";  
        copyFile(src,target);  
    }  
    public static void copyFile(String src,String target)  
        {     
            File srcFile = new File(src);    
               File targetFile = new File(target);    
               try {    
                   InputStream in = new FileInputStream(srcFile);     
                   OutputStream out = new FileOutputStream(targetFile);    
                   byte[] bytes = new byte[1024];    
                   int len = -1;    
                   while((len=in.read(bytes))!=-1)  
                   {    
                       out.write(bytes, 0, len);    
                   }    
                   in.close();    
                   out.close();    
               } catch (FileNotFoundException e) {    
                   e.printStackTrace();    
               } catch (IOException e) {    
                   e.printStackTrace();    
               }    
               System.out.println("文件復(fù)制成功");   
  
  
        }  
                 
    }  

在計(jì)算機(jī)中文件是byte 、byte悲酷、byte地存儲(chǔ)
FileReader在讀取文件的時(shí)候套菜,就是一個(gè)一個(gè)byte地讀取,
BufferedReader則是自帶緩沖區(qū)设易,默認(rèn)緩沖區(qū)大小為8X1024

通俗地講就是:
FileReader在讀取文件的時(shí)候逗柴,一滴一滴地把水從一個(gè)缸復(fù)制到另外一個(gè)缸
BufferedReader則是一桶一桶地把水從一個(gè)缸復(fù)制到另外一個(gè)缸。

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

public class CodeLinesCount {

    public static int countJavaFileLines(String strFileName) throws IOException {
        FileReader fileReader = new FileReader("e:/mycode/" + strFileName);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        int count = 0;
        String strLine = bufferedReader.readLine();
        while (strLine != null)
        {
            count++;
            strLine = bufferedReader.readLine();
        }

        return count;
    }


    public static void main(String[] args) throws IOException {

        File file = new File("e:/mycode/");
        File[] files = file.listFiles();
        int totalCount = 0;
        for(File file1 : files)
        {
            System.out.println(file1.getName());
            int count = countJavaFileLines(file1.getName());
            totalCount += count;
        }

//        int count = countJavaFileLines("MyGuessWord.java");
        System.out.println(totalCount);
    }
}

練習(xí)

寫個(gè)程序讀取以下學(xué)生信息文件亡嫌,計(jì)算出每個(gè)學(xué)生總分嚎于,平均分掘而,名次,寫入到一個(gè)新文件中

學(xué)號(hào) 姓名   語文 數(shù)學(xué) 英語 平均值 總值  排序 
1   李守東   83  73  75 
2   徐賢坤   58  58  87 
3   錢云宋   41  86  90 
4   陳平     83  43  65 
5   金榮權(quán)   93  88  63 
6   陳如棉   99  93  43 
7   章可可   98  62  72 
8   陳偉奔   87  43  76 
9   張如祥   69  58  78 
10  丁尚游   80  56  57 
11  林宏旦   91  90  76 
12  曾上騰   100 96  54 
13  謝作品   82  100 55 
14  溫從衛(wèi)   73  46  101 
15  李明察   81  41  75 
16  彭鴻威   46  46  89 
17  翁文秀   57  43  58 
18  陳家偉   63  58  98 
19  溫正考   100 64  57 
20  周文湘   50  50  79 
21  吳杰     65  65  83 
22  賴登城   60  79  53 
23  聶樹露   51  76  45 
24  張雅琴   68  95  56 
25  曾瑞約   88  63  58 
26  王志強(qiáng)   96  79  78 
27  徐賢所   66  46  74 
28  陳祥梟   82  96  91 
29  溫婷婷   41  73  96 
30  應(yīng)孔余   66  81  71 
31  宋成取   71  68  62 
32  黃益省   65  56  43 
33  陳思文   55  100 44 
34  上官福新 64  62  70 
35  鐘國橫   49  69  56 
36  林型漲   78  73  50 

需要生成的文件

學(xué)號(hào)  姓名  語文  數(shù)學(xué)  英語  平均值 總值  排序
1   李守東 83  73  75  77  231 9   
2   徐賢坤 58  58  87  67  203 21  
3   錢云宋 41  86  90  72  217 15  
4   陳平  83  43  65  63  191 29  
5   金榮權(quán) 93  88  63  81  244 5   
6   陳如棉 99  93  43  78  235 7   
7   章可可 98  62  72  77  232 8   
8   陳偉奔 87  43  76  68  206 19  
9   張如祥 69  58  78  68  205 20  
10  丁尚游 80  56  57  64  193 27  
11  林宏旦 91  90  76  85  257 2   
12  曾上騰 100 96  54  83  250 4   
13  謝作品 82  100 55  79  237 6   
14  溫從衛(wèi) 73  46  101 73  220 11  
15  李明察 81  41  75  65  197 25  
16  彭鴻威 46  46  89  60  181 31  
17  翁文秀 57  43  58  52  158 36  
18  陳家偉 63  58  98  73  219 12  
19  溫正考 100 64  57  73  221 10  
20  周文湘 50  50  79  59  179 32  
21  吳杰  65  65  83  71  213 16  
22  賴登城 60  79  53  64  192 28  
23  聶樹露 51  76  45  57  172 34  
24  張雅琴 68  95  56  73  219 13  
25  曾瑞約 88  63  58  69  209 18  
26  王志強(qiáng) 96  79  78  84  253 3   
27  徐賢所 66  46  74  62  186 30  
28  陳祥梟 82  96  91  89  269 1   
29  溫婷婷 41  73  96  70  210 17  
30  應(yīng)孔余 66  81  71  72  218 14  
31  宋成取 71  68  62  67  201 22  
32  黃益省 65  56  43  54  164 35  
33  陳思文 55  100 44  66  199 24  
34  上官新 64  62  70  65  196 26  
35  鐘國橫 49  69  56  58  174 33  
36  林型漲 78  73  50  67  201 23  

代碼:
學(xué)生類:

package com.company;

public class Student implements Comparable {
    private int sno;
    private String name;
    private int chinese_score;
    private int math_score;
    private int eng_score;
    private int avg_score;
    private int total_score;

    public int getEng_score() {
        return eng_score;
    }

    public void setEng_score(int eng_score) {
        this.eng_score = eng_score;
    }

    public int getSno() {
        return sno;
    }

    public void setSno(int sno) {
        this.sno = sno;
    }

    public String getName() {
        return name;
    }

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

    public int getChinese_score() {
        return chinese_score;
    }

    public void setChinese_score(int chinese_score) {
        this.chinese_score = chinese_score;
    }

    public int getMath_score() {
        return math_score;
    }

    public void setMath_score(int math_score) {
        this.math_score = math_score;
    }

    public int getAvg_score() {
        return avg_score;
    }

    public void setAvg_score(int avg_score) {
        this.avg_score = avg_score;
    }

    public int getTotal_score() {
        return total_score;
    }
    public void setTotal_score(int total_score) {
        this.total_score = total_score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sno=" + sno +
                ", name='" + name + '\'' +
                ", chinese_score=" + chinese_score +
                ", math_score=" + math_score +
                ", eng_score=" + eng_score +
                ", avg_score=" + avg_score +
                ", total_score=" + total_score +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        Student student = (Student)o;
//        if(student.getSno() < this.getSno())
//        {
//            return 5;
//        }
//        else if(student.getSno() > this.getSno())
//        {
//            return -9;
//        }
//        else
//        {
//            return 0;
//        }

//        return this.getName().compareTo(student.getName());//打算按學(xué)生姓名排序
//        return this.getSno() - student.getSno();//打算按學(xué)生學(xué)號(hào)排序
          return student.getTotal_score() - this.getTotal_score();//打算按學(xué)生總分排序
    }
}

主類:

package com.company;

import java.io.*;
import java.util.*;

/**
 * Created by ttc on 2018/1/15.
 */
//        學(xué)號(hào) 姓名   語文 數(shù)學(xué) 英語 平均值 總值  排序
//        1   李守東   83  73  75
//        2   徐賢坤   58  58  87
//        3   錢云宋   41  86  90
//        4   陳平     83  43  65
//        5   金榮權(quán)   93  88  63

public class ComputeStudent {
    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("e:/student_score.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String strStudentInfo = bufferedReader.readLine();//跳過頭部
        List<Student> studentList = new ArrayList<>();
        strStudentInfo = bufferedReader.readLine();
        while(strStudentInfo != null)
        {

            String[] strings = strStudentInfo.split(" ");

            List<String> stringList = new ArrayList<String>();//保存的是一個(gè)學(xué)生的學(xué)號(hào)于购,姓名袍睡,三科成績(jī)

            for(String str : strings)
            {
                if(!str.equals(""))
                {
                    stringList.add(str);
                }
            }

            //創(chuàng)建學(xué)生對(duì)象
            Student student = new Student();

            int sno = Integer.parseInt(stringList.get(0));
            student.setSno(sno);

            student.setName(stringList.get(1));
            int china_score = Integer.parseInt(stringList.get(2));
            student.setChinese_score(china_score);
            int math_score = Integer.parseInt(stringList.get(3));
            student.setMath_score(math_score);
            int eng_score = Integer.parseInt(stringList.get(4));
            student.setEng_score(eng_score);
            student.setTotal_score(china_score+math_score+eng_score);
            student.setAvg_score((china_score+math_score+eng_score)/3);

            studentList.add(student);

            strStudentInfo = bufferedReader.readLine();
        }

        System.out.println(strStudentInfo);

        FileWriter fileWriter = new FileWriter("e:/student_score_new.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);


        bufferedWriter.write("學(xué)號(hào)\t姓名\t語文\t數(shù)學(xué)\t英語\t平均值\t總值\t排序");
        bufferedWriter.newLine();


        List<Student> studentListOld = new ArrayList<>();
        studentListOld.addAll(studentList);//studentListOld里學(xué)生是按照學(xué)號(hào)排序

        Collections.sort(studentList);//studentList里學(xué)生是按照成績(jī)排序

        //保存每個(gè)學(xué)生的名字和排名的鍵值對(duì)
        Map<String,Integer> mapName2Rank = new HashMap<>();

        int index = 1;
        for(Student student : studentList)
        {
            mapName2Rank.put(student.getName(), index++);
        }

        //遍歷list,將list里的每一個(gè)student對(duì)象寫入到文件中
        for(Student student : studentListOld)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(student.getSno());
            stringBuilder.append("\t");
            stringBuilder.append(student.getName());
            stringBuilder.append("\t");
            stringBuilder.append(student.getChinese_score());
            stringBuilder.append("\t");
            stringBuilder.append(student.getMath_score());
            stringBuilder.append("\t");
            stringBuilder.append(student.getEng_score());
            stringBuilder.append("\t");
            stringBuilder.append(student.getAvg_score());
            stringBuilder.append("\t");
            stringBuilder.append(student.getTotal_score());
            stringBuilder.append("\t");

            String strStudentName = student.getName();
            int rank = mapName2Rank.get(strStudentName);//拿到了該名學(xué)生的名次

            stringBuilder.append(rank);
            stringBuilder.append("\t");

            bufferedWriter.write(stringBuilder.toString());
            bufferedWriter.newLine();
        }

        bufferedWriter.flush();

        fileReader.close();
        fileWriter.close();
        bufferedReader.close();
        bufferedWriter.close();
    }
}


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 Test {

public static void main(String[] args) {
    DataOutputStream dos = null;
    DataInputStream dis = null;
    try {
        //寫入基本數(shù)據(jù)類型
        dos = new DataOutputStream(new FileOutputStream("d://dataTest.txt"));
        dos.writeUTF("你好呀腐螟,ok");
        dos.writeInt(18888);
        dos.writeLong(188888);
        dos.writeByte(123);
        dos.writeFloat(1.344f);
        dos.writeBoolean(true);
        dos.writeDouble(1.444444d);
        dos.writeChar(49);
        
        dos.flush();
        dos.close();
        //讀出基本數(shù)據(jù)類型
        dis = new DataInputStream(new FileInputStream("d://dataTest.txt"));

        System.out.println(dis.readUTF());          
        System.out.println(dis.readInt());
        System.out.println(dis.readLong());
        System.out.println(dis.readByte());
        System.out.println(dis.readFloat());
        System.out.println(dis.readBoolean());
        System.out.println(dis.readDouble());
        System.out.println(dis.readChar());
        
        dis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

package com.company;

import java.io.*;

/**
 * Created by ttc on 2018/6/7.
 */
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閱讀 222,946評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件锯仪,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡趾盐,警方通過查閱死者的電腦和手機(jī)庶喜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門椭微,熙熙樓的掌柜王于貴愁眉苦臉地迎上來索赏,“玉大人,你說我怎么就攤上這事蚂子”静” “怎么了斥扛?”我有些...
    開封第一講書人閱讀 169,716評(píng)論 0 364
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我稀颁,道長(zhǎng)芬失,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,222評(píng)論 1 300
  • 正文 為了忘掉前任匾灶,我火速辦了婚禮棱烂,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘阶女。我一直安慰自己颊糜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,223評(píng)論 6 398
  • 文/花漫 我一把揭開白布秃踩。 她就那樣靜靜地躺著衬鱼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪憔杨。 梳的紋絲不亂的頭發(fā)上鸟赫,一...
    開封第一講書人閱讀 52,807評(píng)論 1 314
  • 那天,我揣著相機(jī)與錄音芍秆,去河邊找鬼惯疙。 笑死,一個(gè)胖子當(dāng)著我的面吹牛妖啥,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播对碌,決...
    沈念sama閱讀 41,235評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼荆虱,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了朽们?” 一聲冷哼從身側(cè)響起怀读,我...
    開封第一講書人閱讀 40,189評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎骑脱,沒想到半個(gè)月后菜枷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,712評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡叁丧,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,775評(píng)論 3 343
  • 正文 我和宋清朗相戀三年啤誊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拥娄。...
    茶點(diǎn)故事閱讀 40,926評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蚊锹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出稚瘾,到底是詐尸還是另有隱情牡昆,我是刑警寧澤,帶...
    沈念sama閱讀 36,580評(píng)論 5 351
  • 正文 年R本政府宣布摊欠,位于F島的核電站丢烘,受9級(jí)特大地震影響柱宦,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜播瞳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,259評(píng)論 3 336
  • 文/蒙蒙 一掸刊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧狐史,春花似錦痒给、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,750評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至姜贡,卻和暖如春试吁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背楼咳。 一陣腳步聲響...
    開封第一講書人閱讀 33,867評(píng)論 1 274
  • 我被黑心中介騙來泰國打工熄捍, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人母怜。 一個(gè)月前我還...
    沈念sama閱讀 49,368評(píng)論 3 379
  • 正文 我出身青樓余耽,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親苹熏。 傳聞我的和親對(duì)象是個(gè)殘疾皇子碟贾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,930評(píng)論 2 361

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

  • 一、流的概念和作用轨域。 流是一種有順序的袱耽,有起點(diǎn)和終點(diǎn)的字節(jié)集合,是對(duì)數(shù)據(jù)傳輸?shù)目偝苫虺橄蟾煞ⅰ<磾?shù)據(jù)在兩設(shè)備之間的傳輸...
    布魯斯不吐絲閱讀 10,062評(píng)論 2 95
  • IO簡(jiǎn)單概述 IO解決問題 : 解決設(shè)備與設(shè)備之間的數(shù)據(jù)傳輸問題(硬盤 -> 內(nèi)存 內(nèi)存 -> 硬盤) 讀和寫文...
    奮斗的老王閱讀 3,444評(píng)論 0 53
  • 最近在做一個(gè) WEB 項(xiàng)目朱巨,需要調(diào)用 OCX 進(jìn)行連接讀卡器讀卡。本來并不想用 OCX 技術(shù)枉长,因?yàn)?ActiveX...
    安易學(xué)車閱讀 2,223評(píng)論 1 5
  • 喜歡陽光冀续,有陽光的地方,我的夢(mèng)想就不會(huì)孤單搀暑,就算孤身一人走完了所有的路沥阳,也會(huì)貪戀明媚的陽光,因?yàn)闀?huì)回歸最初的...
    空空君閱讀 305評(píng)論 0 3