java文件內容:讀取與寫入

對於java文件讀取一直比較迷糊,整理了下,日後可以直接翻看。

package baixiaosheng;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class JavaReadAndWriteFile {
    private static String filePath = "E:/learn/test.txt";

    /**
     * 以字節爲單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件
     * 
     * @param fileName
     */
    public static void readFileByBytes(String filePath) {
        InputStream inputStream = null;

        /*
         * try { System.out.println("以字節爲單位讀取文件內容,一次讀取一個字節:"); inputStream = new
         * FileInputStream(new File(fileName)); int tempbyte; while ((tempbyte =
         * inputStream.read()) != -1) { System.out.write(tempbyte); }
         * inputStream.close(); } catch (IOException e) { e.printStackTrace(); }
         */

        try {
            System.out.println("以字節爲單位讀取文件內容,一次讀取多個字節:");
            inputStream = new FileInputStream(new File(filePath));
            byte[] tempbytes = new byte[100];
            int byteNumRead = 0;
            while ((byteNumRead = inputStream.read(tempbytes)) != -1) {
                System.out.write(tempbytes, 0, byteNumRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println();
    }

    /**
     * 以字符爲單位讀取文件,常用於讀文本,數字等類型的文件
     * 
     * @param fileName
     */
    public static void readFileByChars(String filePath) {
        Reader reader = null;

        /*try {
            System.out.println("以字符爲單位讀取文件內容,一次讀一個字符:");
            reader = new InputStreamReader(new FileInputStream(new File(
                    filePath)));
            int tempChar = 0;
            while ((tempChar = reader.read()) != -1) {
                // 對於windows下,\r\n這兩個字符在一起時,表示一個換行; 但如果這兩個字符分開顯示時,會換兩次行。  
                // 因此,屏蔽掉\r,或者屏蔽\n。否則,將會多出很多空行。 
                if((char)tempChar != '\r'){
                    System.out.print((char)tempChar);
                } 
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        try {
            System.out.println("以字符爲單位讀取文件內容,一次讀多個字符:");
            reader = new InputStreamReader(new FileInputStream(new File(
                    filePath)));
            char[] tempchars = new char[100];
            int charNumRead = 0;
            // 讀入多個字符到字符數組中,charNumRead爲一次讀取字符數
            while ((charNumRead = reader.read(tempchars)) != -1) {
                if(charNumRead==tempchars.length && (tempchars[tempchars.length - 1] != '\r')){
                    System.out.println(tempchars);
                }else {
                    for(char c:tempchars){
                        if(c == '\r'){
                            continue;
                        }else {
                            System.out.print(c);
                        }
                    }
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {  
            if (reader != null) {  
                try {  
                    reader.close();  
                } catch (IOException e1) {}
            }
        }
    }

    /**
     * 以行爲單位讀取文件,常用於讀面向行的格式化文件
     * @param filePath
     */
    public static void readFileByLines(String filePath) {
        BufferedReader bufferedReader = null;
        try {
            System.out.println("以行爲單位讀取文件內容,一次讀一整行:");
            bufferedReader = new BufferedReader(new FileReader(new File(
                    filePath)));
            String tempString;
            int line = 1;
            // 一次讀入一行,直到讀入null爲文件結束
            while ((tempString = bufferedReader.readLine()) != null) {
                System.out.println("第" + line + "行內容:" + tempString);
                line++;
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {  
            if (bufferedReader != null) {  
                try {  
                    bufferedReader.close();  
                } catch (IOException e1) {}
            }
        }
    }

    /**
     * 寫內容到文件
     * @param filePath
     * @param content
     */
    public static void writeContenToFile(String filePath,String content){
        FileWriter fileWriter = null;
        try {
            //打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
            fileWriter = new FileWriter(filePath,true);
            fileWriter.append(content);
            System.out.println("文件寫入成功...請打開文件查看.");
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {}
            }
        }
    }
    
    public static void main(String[] args) {
        JavaReadAndWriteFile.readFileByBytes(filePath);
        JavaReadAndWriteFile.readFileByChars(filePath);
        JavaReadAndWriteFile.readFileByLines(filePath);
        JavaReadAndWriteFile.writeContenToFile(filePath, " zyb");
    }

}

看到的另外一個大神對java  io流的整理挺好的,文章標題:深入理解JAVA中的IO

 

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