Java的文件多種讀寫操作

  1. import java.io.File;  

  2. import java.io.FileInputStream;  

  3. import java.io.FileNotFoundException;  

  4. import java.io.FileOutputStream;  

  5. import java.io.IOException;  

  6. import java.io.InputStreamReader;  

  7.   

  8. public class testFile {  

  9.     public static void main(String[] args) {   

  10.         // file(內存)----輸入流---->【程序】----輸出流---->file(內存)  

  11.         File file = new File("d:/temp""addfile.txt");  

  12.         try {  

  13.             file.createNewFile(); // 創建文件  

  14.         } catch (IOException e) {  

  15.             e.printStackTrace();  

  16.         }  

  17.   

  18.         // 向文件寫入內容(輸出流)  

  19.         String str = "親愛的小南瓜!";  

  20.         byte bt[] = new byte[1024];  

  21.         bt = str.getBytes();  

  22.         try {  

  23.             FileOutputStream in = new FileOutputStream(file);  

  24.             try {  

  25.                 in.write(bt, 0, bt.length);  

  26.                 in.close();  

  27.                 // boolean success=true;  

  28.                 // System.out.println("寫入文件成功");  

  29.             } catch (IOException e) {  

  30.                 e.printStackTrace();  

  31.             }  

  32.         } catch (FileNotFoundException e) {  

  33.             e.printStackTrace();  

  34.         }  

  35.         try {  

  36.             // 讀取文件內容 (輸入流)  

  37.             FileInputStream out = new FileInputStream(file);  

  38.             InputStreamReader isr = new InputStreamReader(out);  

  39.             int ch = 0;  

  40.             while ((ch = isr.read()) != -1) {  

  41.                 System.out.print((char) ch);  

  42.             }  

  43.         } catch (Exception e) {  

  44.             // TODO: handle exception  

  45.         }  

  46.     }  

  47. }  



java中多種方式讀文件



[java] view plain copy

  1. //------------------參考資料---------------------------------  

  2. //  

  3. //1、按字節讀取文件內容  

  4. //2、按字符讀取文件內容  

  5. //3、按行讀取文件內容  

  6. //4、隨機讀取文件內容  

  7.   

  8. public class ReadFromFile {  

  9.     /** 

  10.      * 以字節爲單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。 

  11.      *  

  12.      * @param fileName 

  13.      *            文件的名 

  14.      */  

  15.     public static void readFileByBytes(String fileName) {  

  16.         File file = new File(fileName);  

  17.         InputStream in = null;  

  18.         try {  

  19.             System.out.println("以字節爲單位讀取文件內容,一次讀一個字節:");  

  20.             // 一次讀一個字節  

  21.             in = new FileInputStream(file);  

  22.             int tempbyte;  

  23.             while ((tempbyte = in.read()) != -1) {  

  24.                 System.out.write(tempbyte);  

  25.             }  

  26.             in.close();  

  27.         } catch (IOException e) {  

  28.             e.printStackTrace();  

  29.             return;  

  30.         }  

  31.         try {  

  32.             System.out.println("以字節爲單位讀取文件內容,一次讀多個字節:");  

  33.             // 一次讀多個字節  

  34.             byte[] tempbytes = new byte[100];  

  35.             int byteread = 0;  

  36.             in = new FileInputStream(fileName);  

  37.             ReadFromFile.showAvailableBytes(in);  

  38.             // 讀入多個字節到字節數組中,byteread爲一次讀入的字節數  

  39.             while ((byteread = in.read(tempbytes)) != -1) {  

  40.                 System.out.write(tempbytes, 0, byteread);  

  41.             }  

  42.         } catch (Exception e1) {  

  43.             e1.printStackTrace();  

  44.         } finally {  

  45.             if (in != null) {  

  46.                 try {  

  47.                     in.close();  

  48.                 } catch (IOException e1) {  

  49.                 }  

  50.             }  

  51.         }  

  52.     }  

  53.   

  54.     /** 

  55.      * 以字符爲單位讀取文件,常用於讀文本,數字等類型的文件 

  56.      *  

  57.      * @param fileName 

  58.      *            文件名 

  59.      */  

  60.     public static void readFileByChars(String fileName) {  

  61.         File file = new File(fileName);  

  62.         Reader reader = null;  

  63.         try {  

  64.             System.out.println("以字符爲單位讀取文件內容,一次讀一個字節:");  

  65.             // 一次讀一個字符  

  66.             reader = new InputStreamReader(new FileInputStream(file));  

  67.             int tempchar;  

  68.             while ((tempchar = reader.read()) != -1) {  

  69.                 // 對於windows下,rn這兩個字符在一起時,表示一個換行。  

  70.                 // 但如果這兩個字符分開顯示時,會換兩次行。  

  71.                 // 因此,屏蔽掉r,或者屏蔽n。否則,將會多出很多空行。  

  72.                 if (((char) tempchar) != 'r') {  

  73.                     System.out.print((char) tempchar);  

  74.                 }  

  75.             }  

  76.             reader.close();  

  77.         } catch (Exception e) {  

  78.             e.printStackTrace();  

  79.         }  

  80.         try {  

  81.             System.out.println("以字符爲單位讀取文件內容,一次讀多個字節:");  

  82.             // 一次讀多個字符  

  83.             char[] tempchars = new char[30];  

  84.             int charread = 0;  

  85.             reader = new InputStreamReader(new FileInputStream(fileName));  

  86.             // 讀入多個字符到字符數組中,charread爲一次讀取字符數  

  87.             while ((charread = reader.read(tempchars)) != -1) {  

  88.                 // 同樣屏蔽掉r不顯示  

  89.                 if ((charread == tempchars.length)  

  90.                         && (tempchars[tempchars.length - 1] != 'r')) {  

  91.                     System.out.print(tempchars);  

  92.                 } else {  

  93.                     for (int i = 0; i < charread; i++) {  

  94.                         if (tempchars[i] == 'r') {  

  95.                             continue;  

  96.                         } else {  

  97.                             System.out.print(tempchars[i]);  

  98.                         }  

  99.                     }  

  100.                 }  

  101.             }  

  102.         } catch (Exception e1) {  

  103.             e1.printStackTrace();  

  104.         } finally {  

  105.             if (reader != null) {  

  106.                 try {  

  107.                     reader.close();  

  108.                 } catch (IOException e1) {  

  109.                 }  

  110.             }  

  111.         }  

  112.     }  

  113.   

  114.     /** 

  115.      * 以行爲單位讀取文件,常用於讀面向行的格式化文件 

  116.      *  

  117.      * @param fileName 

  118.      *            文件名 

  119.      */  

  120.     public static void readFileByLines(String fileName) {  

  121.         File file = new File(fileName);  

  122.         BufferedReader reader = null;  

  123.         try {  

  124.             System.out.println("以行爲單位讀取文件內容,一次讀一整行:");  

  125.             reader = new BufferedReader(new FileReader(file));  

  126.             String tempString = null;  

  127.             int line = 1;  

  128.             // 一次讀入一行,直到讀入null爲文件結束  

  129.             while ((tempString = reader.readLine()) != null) {  

  130.                 // 顯示行號  

  131.                 System.out.println("line " + line + ": " + tempString);  

  132.                 line++;  

  133.             }  

  134.             reader.close();  

  135.         } catch (IOException e) {  

  136.             e.printStackTrace();  

  137.         } finally {  

  138.             if (reader != null) {  

  139.                 try {  

  140.                     reader.close();  

  141.                 } catch (IOException e1) {  

  142.                 }  

  143.             }  

  144.         }  

  145.     }  

  146.   

  147.     /** 

  148.      * 隨機讀取文件內容 

  149.      *  

  150.      * @param fileName 

  151.      *            文件名 

  152.      */  

  153.     public static void readFileByRandomAccess(String fileName) {  

  154.         RandomAccessFile randomFile = null;  

  155.         try {  

  156.             System.out.println("隨機讀取一段文件內容:");  

  157.             // 打開一個隨機訪問文件流,按只讀方式  

  158.             randomFile = new RandomAccessFile(fileName, "r");  

  159.             // 文件長度,字節數  

  160.             long fileLength = randomFile.length();  

  161.             // 讀文件的起始位置  

  162.             int beginIndex = (fileLength > 4) ? 4 : 0;  

  163.             // 將讀文件的開始位置移到beginIndex位置。  

  164.             randomFile.seek(beginIndex);  

  165.             byte[] bytes = new byte[10];  

  166.             int byteread = 0;  

  167.             // 一次讀10個字節,如果文件內容不足10個字節,則讀剩下的字節。  

  168.             // 將一次讀取的字節數賦給byteread  

  169.             while ((byteread = randomFile.read(bytes)) != -1) {  

  170.                 System.out.write(bytes, 0, byteread);  

  171.             }  

  172.         } catch (IOException e) {  

  173.             e.printStackTrace();  

  174.         } finally {  

  175.             if (randomFile != null) {  

  176.                 try {  

  177.                     randomFile.close();  

  178.                 } catch (IOException e1) {  

  179.                 }  

  180.             }  

  181.         }  

  182.     }  

  183.   

  184.     /** 

  185.      * 顯示輸入流中還剩的字節數 

  186.      *  

  187.      * @param in 

  188.      */  

  189.     private static void showAvailableBytes(InputStream in) {  

  190.         try {  

  191.             System.out.println("當前字節輸入流中的字節數爲:" + in.available());  

  192.         } catch (IOException e) {  

  193.             e.printStackTrace();  

  194.         }  

  195.     }  

  196.   

  197.     public static void main(String[] args) {  

  198.         String fileName = "C:/temp/newTemp.txt";  

  199.         ReadFromFile.readFileByBytes(fileName);  

  200.         ReadFromFile.readFileByChars(fileName);  

  201.         ReadFromFile.readFileByLines(fileName);  

  202.         ReadFromFile.readFileByRandomAccess(fileName);  

  203.     }  

  204. }  



[java] view plain copy

  1. //二、將內容追加到文件尾部  

  2. import java.io.FileWriter;  

  3. import java.io.IOException;  

  4. import java.io.RandomAccessFile;  

  5.   

  6. /** 

  7.  * 將內容追加到文件尾部 

  8.  */  

  9. public class AppendToFile {  

  10.     /** 

  11.      * A方法追加文件:使用RandomAccessFile 

  12.      *  

  13.      * @param fileName 

  14.      *            文件名 

  15.      * @param content 

  16.      *            追加的內容 

  17.      */  

  18.     public static void appendMethodA(String fileName,  

  19.   

  20.     String content) {  

  21.         try {  

  22.             // 打開一個隨機訪問文件流,按讀寫方式  

  23.             RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");  

  24.             // 文件長度,字節數  

  25.             long fileLength = randomFile.length();  

  26.             // 將寫文件指針移到文件尾。  

  27.             randomFile.seek(fileLength);  

  28.             randomFile.writeBytes(content);  

  29.             randomFile.close();  

  30.         } catch (IOException e) {  

  31.             e.printStackTrace();  

  32.         }  

  33.     }  

  34.   

  35.     /** 

  36.      * B方法追加文件:使用FileWriter 

  37.      *  

  38.      * @param fileName 

  39.      * @param content 

  40.      */  

  41.     public static void appendMethodB(String fileName, String content) {  

  42.         try {  

  43.             // 打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件  

  44.             FileWriter writer = new FileWriter(fileName, true);  

  45.             writer.write(content);  

  46.             writer.close();  

  47.         } catch (IOException e) {  

  48.             e.printStackTrace();  

  49.         }  

  50.     }  

  51.   

  52.     public static void main(String[] args) {  

  53.         String fileName = "C:/temp/newTemp.txt";  

  54.         String content = "new append!";  

  55.         // 按方法A追加文件  

  56.         AppendToFile.appendMethodA(fileName, content);  

  57.         AppendToFile.appendMethodA(fileName, "append end. n");  

  58.         // 顯示文件內容  

  59.         ReadFromFile.readFileByLines(fileName);  

  60.         // 按方法B追加文件  

  61.         AppendToFile.appendMethodB(fileName, content);  

  62.         AppendToFile.appendMethodB(fileName, "append end. n");  

  63.         // 顯示文件內容  

  64.         ReadFromFile.readFileByLines(fileName);  

  65.     }  

  66. }  


java 寫文件的三種方法比較



[java] view plain copy

  1. import java.io.File;     

  2.   

  3. import java.io.FileOutputStream;     

  4.   

  5. import java.io.*;     

  6.   

  7. public class FileTest {     

  8.   

  9.     public FileTest() {     

  10.   

  11.     }     

  12.   

  13.     public static void main(String[] args) {     

  14.   

  15.         FileOutputStream out = null;     

  16.   

  17.         FileOutputStream outSTr = null;     

  18.   

  19.         BufferedOutputStream Buff=null;     

  20.   

  21.         FileWriter fw = null;     

  22.   

  23.         int count=1000;//寫文件行數     

  24.   

  25.         try {     

  26.   

  27.             out = new FileOutputStream(new File(“C:/add.txt”));     

  28.   

  29.             long begin = System.currentTimeMillis();     

  30.   

  31.             for (int i = 0; i < count; i++) {     

  32.   

  33.                 out.write(“測試java 文件操作\r\n”.getBytes());     

  34.   

  35.             }     

  36.   

  37.             out.close();     

  38.   

  39.             long end = System.currentTimeMillis();     

  40.   

  41.             System.out.println(“FileOutputStream執行耗時:” + (end - begin) + ” 豪秒”);     

  42.   

  43.             outSTr = new FileOutputStream(new File(“C:/add0.txt”));     

  44.   

  45.              Buff=new BufferedOutputStream(outSTr);     

  46.   

  47.             long begin0 = System.currentTimeMillis();     

  48.   

  49.             for (int i = 0; i < count; i++) {     

  50.   

  51.                 Buff.write(“測試java 文件操作\r\n”.getBytes());     

  52.   

  53.             }     

  54.   

  55.             Buff.flush();     

  56.   

  57.             Buff.close();     

  58.   

  59.             long end0 = System.currentTimeMillis();     

  60.   

  61.             System.out.println(“BufferedOutputStream執行耗時:” + (end0 - begin0) + ” 豪秒”);     

  62.   

  63.             fw = new FileWriter(“C:/add2.txt”);     

  64.   

  65.             long begin3 = System.currentTimeMillis();     

  66.   

  67.             for (int i = 0; i < count; i++) {     

  68.   

  69.                 fw.write(“測試java 文件操作\r\n”);     

  70.   

  71.             }     

  72.   

  73.                         fw.close();     

  74.   

  75.             long end3 = System.currentTimeMillis();     

  76.   

  77.             System.out.println(“FileWriter執行耗時:” + (end3 - begin3) + ” 豪秒”);     

  78.   

  79.         } catch (Exception e) {     

  80.   

  81.             e.printStackTrace();     

  82.   

  83.         }     

  84.   

  85.         finally {     

  86.   

  87.             try {     

  88.   

  89.                 fw.close();     

  90.   

  91.                 Buff.close();     

  92.   

  93.                 outSTr.close();     

  94.   

  95.                 out.close();     

  96.   

  97.             } catch (Exception e) {     

  98.   

  99.                 e.printStackTrace();     

  100.   

  101.             }     

  102.   

  103.         }     

  104.   

  105.     }     

  106.   

  107. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章