Java讀寫檔案方法總結(推薦)_java

來源:互聯網
上載者:User

Java的讀寫檔案方法在工作中相信有很多的用處的,本人在之前包括現在都在使用Java的讀寫檔案方法來處理資料方面的輸入輸出,確實很方便。奈何我的記性實在是叫人著急,很多時候既然都會想不起來怎麼寫了,不過我的Java代碼量也實在是少的可憐,所以應該多多練習。這裡做一個總結,集中在一起方面今後查看。

Java讀檔案

package 天才白癡夢;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.RandomAccessFile;import java.io.Reader;public class JavaIO {    /**   * 採用的是作業系統底層預設的編碼方式,GBK等,非UTF8   * */    /**   * 以位元組為單位讀取檔案內容,常用於讀取二進位檔案,比如圖片、影像、聲音等檔案   * */  public static void readFileByBytes(String filename) {    File file=new File(filename);    FileInputStream in=null;    try {      System.out.println("以位元組為單位讀取檔案,一次讀一個位元組: ");      in=new FileInputStream(file);      int temp=0;      while ((temp=in.read()) != -1) {        System.out.println(temp);      }      in.close();    } catch (IOException e) {      e.printStackTrace();      return ;    }    try {      System.out.println("以位元組為單位讀取檔案,一次讀多個位元組: ");      byte[] temp=new byte[100];      int byteread=0;      in=new FileInputStream(file);      JavaIO.showAvailableBytes(in);      while ((byteread=in.read(temp)) != -1) {        System.out.write(temp,0,byteread);      }    } catch (Exception e1) {      e1.printStackTrace();    } finally {      if (in != null) {        try {          in.close();        } catch (IOException e1) {                  }      }    }  }  /**   * 以字元為單位讀取檔案,常用於讀文本,數字等類型的檔案   * */  public static void readFileByChar(String filename) {    File file=new File(filename);    Reader reader=null;    try {      System.out.println("以字元為單位讀取檔案內容,一次一個位元組:");      //InputStreamReader類:是位元組向字元轉換的橋樑      reader=new InputStreamReader(new FileInputStream(file));      int temp;      while ((temp=reader.read()) != -1) {        if (((char)temp) != '\r') {          System.out.println((char)temp);        }      }       reader.close();    } catch (Exception e) {      e.printStackTrace();    }    try {      System.out.println("以字元為單位讀取檔案內容,一次讀多個位元組: ");      char[] temp=new char[30];      int charread=0;      reader=new InputStreamReader(new FileInputStream(filename));      while ((charread=reader.read(temp)) != -1) {        if ((charread == temp.length) && (temp[temp.length-1]!='\r')) {          System.out.println(temp);        } else {          for (int i=0; i<charread; i++) {            if (temp[i] == '\r') {              break;            } else {              System.out.println(temp[i]);            }          }        }      }    } catch (Exception e) {      e.printStackTrace();    } finally {      if (reader != null) {        try {          reader.close();        } catch (IOException e) {                  }      }    }  }  /**   * 以行為單位讀取檔案,常用於讀面向行的格式檔案   * */  public static void readFileByLine(String filename) {    File file=new File(filename);    BufferedReader reader=null;    try {      System.out.println("以行為單位讀取檔案內容,一次讀一整行: ");      reader=new BufferedReader(new FileReader(file));      String temp=null;      int line=1;      while ((temp=reader.readLine()) != null) {        System.out.println("line " + line + ": " + temp);        line++;      }      reader.close();    } catch (IOException e) {      e.printStackTrace();    } finally {      if (reader != null) {        try {          reader.close();        } catch (IOException e) {                  }      }    }  }  /**   * 隨機讀取檔案內容   * */  public static void readFileByRandomAccess(String filename) {    RandomAccessFile randomfile=null;    try {      System.out.println("隨機讀取一段檔案內容");      randomfile=new RandomAccessFile(filename,"r");      long fileLength=randomfile.length();      int beginIndex=(fileLength > 4 ? 4 : 0);      randomfile.seek(beginIndex);      byte[] bytes=new byte[10];      int byteread=0;      while ((byteread=randomfile.read(bytes)) != -1) {        System.out.write(bytes,0,byteread);      }    } catch (IOException e) {      e.printStackTrace();    } finally {      if (randomfile != null) {        try {          randomfile.close();        } catch (IOException e) {                  }      }    }  }  private static void showAvailableBytes(InputStream in) {    try {      System.out.println("當前位元組輸入資料流中的位元組數為:" + in.available());    } catch (IOException e) {      e.printStackTrace();    }  }  public static void main(String[] args) {    String filename="E:\\BaiYiShaoNian.txt";    JavaIO.readFileByBytes(filename);    JavaIO.readFileByChar(filename);    JavaIO.readFileByLine(filename);    JavaIO.readFileByRandomAccess(filename);  }}

Java寫檔案

package 天才白癡夢;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.OutputStreamWriter;public class JavaIO2 {  public static void main(String[] args) throws IOException {    String Path="E:\\天才白癡夢\\JAVA";    File file=new File("E:\\天才白癡夢\\JAVA","BaiYiShaoNian.txt");    if (!file.exists()) {      try {        file.createNewFile();      } catch (IOException e) {        e.printStackTrace();      }    }    /**     * Java寫入檔案的三種方法     * */    FileOutputStream fos=null;    BufferedWriter bw=null;    FileWriter fw=null;    int value=1000;        try {      fos=new FileOutputStream(new File(Path+"fos.txt"));      long begin=System.currentTimeMillis();      for (int i=1; i<=value; i++) {        fos.write(5);      }      long end=System.currentTimeMillis();      System.out.println("TheCostTime of FileOutputStream is : " + (end-begin));      fos.close();            bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(Path+"br.txt")),"UTF8"));      begin=System.currentTimeMillis();      for (int i=1; i<=value; i++) {        bw.write(5);        bw.newLine();      }      bw.close();      end=System.currentTimeMillis();      System.out.println("TheCostTime of BufferedWriter is : " + (end-begin));            fw=new FileWriter(Path+"fw.txt");      begin=System.currentTimeMillis();      for (int i=1; i<=value; i++) {        fw.write(5);              }      fw.close();      end=System.currentTimeMillis();      System.out.println("TheCostTime of FileWriter is : " + (end-begin));                } catch (Exception e) {      // TODO Auto-generated catch block      e.printStackTrace();    } finally {      try {        fos.close(); //FileOutputStream        bw.close(); //BufferedWriter        fw.close(); //FileWriter      } catch (Exception e) {        e.printStackTrace();      }    }      }}

以上這篇Java讀寫檔案方法總結(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.