Java开发之I/O读取文件实例详解

在java开发或者android开发中,读取文件是不可避免的,以下对java开发中读取文件做了归纳和详解:

 

1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容

4、随机读取文件内容 

package com.czm.io;



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;



import javax.swing.Box.Filler;



/**

 * 1、按字节读取文件内容

 * 2、按字符读取文件内容

 * 3、按行读取文件内容

 * 4、随机读取文件内容 

 * @author caizhiming

 *

 */

public class ReadFromFile {



     /**

     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

     * @author caizhiming

     */

    public static void readFileByBytes(String fileName){

        System.out.println("\n\n================按字节读取=================");

        File file = new File(fileName);

        InputStream is = null;

        try{

            System.out.println("以字节为单位读取文件内容,一次读一个字节:");

            //一次读一个字节

            is = new FileInputStream(file);

            int tempByte;

            

            while((tempByte = is.read()) != -1){

                System.out.write(tempByte);

                //System.out.print("=");

            }

            is.close();

        }catch(IOException e){

            e.printStackTrace();

            return;

        }

        try{

            System.out.println("\n以字节为单位读取文件内容,一次读多个字节:");

             // 一次读多个字节

            byte[] tempBytes = new byte[100];

            int byteRead = 0;

            is = new FileInputStream(file);

            ReadFromFile.showAvailableBytes(is);

            // 读入多个字节到字节数组中,byteRead为一次读入的字节数

            while((byteRead = is.read(tempBytes)) != -1){

                System.out.write(tempBytes, 0, byteRead);

                //System.out.print("=");

            }

        }catch(IOException e){

            e.printStackTrace();

        }finally{

            if(is != null){

                try {

                    is.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

        

        

         

    }

    /**

     * 以字符为单位读取文件,常用于读文本,数字等类型的文件

     * @author caizhiming

     */

    public static void readFileByChars(String fileName){

        System.out.println("\n\n================按字符读取=================");

        

        File file = new File(fileName);

        Reader reader = null;

        try{

            System.out.println("\n以字符为单位读取文件内容,一次读一个字节:");

            // 一次读一个字符

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

            int tempChar;

            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("\n以字符为单位读取文件内容,一次读多个字节:");

            // 一次读多个字符

            char[] tempChars = new char[30];

            int charRead = 0;

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

            // 读入多个字符到字符数组中,charRead为一次读取字符数

            while((charRead = reader.read(tempChars)) != -1){

                // 同样屏蔽掉\r不显示

                if((charRead == tempChars.length) && (tempChars[tempChars.length - 1] != '\r')){

                    System.out.print(tempChars);

                }else{

                    for(int i=0;i<charRead;i++){

                        if(tempChars[i]=='\r'){

                            continue;

                        }else{

                            System.out.print(tempChars[i]);

                        }

                    }

                }

            }

        } catch (IOException e) {

            // TODO: handle exception

            e.printStackTrace();

        }finally{

            if(reader != null){

                try {

                    reader.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

    /**

     * 以行为单位读取文件,常用于读面向行的格式化文件

     * @author caizhiming

     */

    public static void readFileByLines(String fileName){

        System.out.println("\n\n================按行读取=================");

        File file = new File(fileName);

        BufferedReader reader = null;

        

        try {

            System.out.println("以行为单位读取文件内容,一次读一整行:");

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

            String tempString = null;

            int line = 1;

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

                // 显示行号

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

                line++;

            }

            reader.close();

        } catch (Exception e) {

            // TODO: handle exception

            e.printStackTrace();

        }finally{

            if(reader != null){

                try {

                    reader.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

    /**

     * 随机读取文件内容

     * @author caizhiming

     */

    public static void readFileByRandomAccess(String fileName){

        System.out.println("\n\n================随机读取=================");

         RandomAccessFile randomAccessFile = null;

         try {

             System.out.println("随机读取一段文件内容:");

            // 打开一个随机访问文件流,按只读方式

             randomAccessFile  = new RandomAccessFile(fileName, "r");

            // 文件长度,字节数

             int fileLength = (int) randomAccessFile.length();

             //读文件的起始位置

             int beginPos = (fileLength > 5) ? 5:0;

             //将文件的开始位置移到beginPos位置

             randomAccessFile.seek(beginPos);

             

             byte[] bytes = new byte[12];

             int byteRead = 0;

            // 一次读10个字节,如果文件内容不足12个字节,则读剩下的字节。

            // 将一次读取的字节数赋给byteRead

             while((byteRead = randomAccessFile.read(bytes)) != -1){

                 System.out.write(bytes, 0, byteRead);

             }

             

        } catch (Exception e) {

            // TODO: handle exception

            e.printStackTrace();

        }finally{

            if(randomAccessFile != null){

                try {

                    randomAccessFile.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

    /**

     * 显示输入流中还剩的字节数

     */

    private static void showAvailableBytes(InputStream is) {

        try {

            System.out.println("当前字节输入流中的字节数为:" + is.available());

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    

}

 

5、将内容追加到文件尾部

package com.czm.io;



import java.io.FileWriter;

import java.io.IOException;

import java.io.RandomAccessFile;



/**

 * 将内容追加到文件尾部

 * @author caizhiming

 *

 */

public class AppendToFile {



     /**

     * 追加文件:使用RandomAccessFile

     * @author caizhiming

     */

    public static void appendByRandomAccessFile(String fileName, String content){

        System.out.println("\n\n================使用RandomAccessFile追加内容到文件尾部=================");

        RandomAccessFile randomAccessFile = null;

        try {

            //属性必须设置为rw,即为可写可读属性

            randomAccessFile  = new RandomAccessFile(fileName, "rw");

            int fileLength = (int) randomAccessFile.length();

            

            //将写文件指针移动到文件尾

            randomAccessFile.seek(fileLength);

            //randomAccessFile.writeBytes(content);

            byte[] bytes = content.getBytes("UTF-8");

            randomAccessFile.write(bytes);

            

        } catch (IOException e) {

            // TODO: handle exception

            e.printStackTrace();

        }finally{

            if(randomAccessFile != null){

                try {

                    randomAccessFile.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

     /**

     * 追加文件:使用FileWriter

     * @author caizhiming

     */

    public static void appendByFileWriter(String fileName, String content){

        System.out.println("\n\n================使用FileWriter追加内容到文件尾部=================");

        FileWriter fileWriter = null;

        try {

            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件

            fileWriter = new FileWriter(fileName, true);

            fileWriter.write(content);

        } catch (Exception e) {

            // TODO: handle exception

            e.printStackTrace();

        }finally{

            if(fileWriter != null){

                try {

                    fileWriter.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

        

    }

}

 

最后测试用例:

public class IOTester {

    public static void main(String[] args){

        String file = "D:/test/iotest.txt";

        ReadFromFile.readFileByBytes(file);

        

        ReadFromFile.readFileByChars(file);

        ReadFromFile.readFileByLines(file);

        ReadFromFile.readFileByRandomAccess(file);

        

        AppendToFile.appendByRandomAccessFile(file, "\n我是采用RandomAccessFile方法追加进来的内容");

        AppendToFile.appendByFileWriter(file, "\n我是采用FileWriter方法追加进来的内容");

    }

}

下面是测试截图:

Java开发之I/O读取文件实例详解

 

你可能感兴趣的:(java开发)