Java文件读写五种

注释:

采用的是操作系统底层默认的编码方式,GBK等,非UTF8

1. 以字节为单位读取文件内容,常用于读取二进制文件,比如图片、影像、声音等文件

1.1 以字节为单位读取文件,一次读一个字节

1.2 以字节为单位读取文件,一次读多个字节

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

2.1 以字符为单位读取文件内容,一次一个字节

2.2 以字符为单位读取文件内容,一次读多个字节

3. 以行为单位读取文件,常用于读面向行的格式化文件:以行为单位读取文件内容,一次读一整行

4. 随机读取文件内容:随机读取一段文件内容,字符读

5. 使用Java.nio ByteBuffer

结果:

1. 运行以下代码,可观察输出结果,采用字节读取且一次读一个字节(Byte) 时,读出的是原内容的字节编码

2. 使用新io(nio),使用缓冲区读写,比字符字节读取更高效

代码:

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 java.nio.ByteBuffer;  
import java.nio.channels.FileChannel;

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("\n以字符为单位读取文件内容,一次一个字节:");
            //InputStreamReader类:是字节向字符转换的桥梁
            reader = new InputStreamReader(new FileInputStream(file));
            int temp;
            while ((temp = reader.read()) != -1) {
                if (((char)temp) != '\r') {
                    System.out.print((char)temp);
                }
            } 
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("\n以字符为单位读取文件内容,一次读多个字节: ");
            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.print(temp);
                } else {
                    for (int i = 0; i < charread; i++) {
                    	System.out.print(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("\n以行为单位读取文件内容,一次读一整行: ");
            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) {
                    
                }
            }
        }
    }
    
    /**
     * 使用Java.nio ByteBuffer
     * */
    public static void readFileByBybeBuffer(String filePath) {  
        FileInputStream in = null;  
        
        try { 
        	System.out.println("\n缓冲区nio读字节");
            // 获取源文件和目标文件的输入输出流    
            in = new FileInputStream(filePath);  
            
            // 获取输入输出通道  
            FileChannel fcIn = in.getChannel();  
             
            ByteBuffer buffer = ByteBuffer.allocate(1024);  
            while (true) {  
                // clear方法重设缓冲区,使它可以接受读入的数据  
                buffer.clear();  
                // 从输入通道中将数据读到缓冲区  
                int r = fcIn.read(buffer);  
                if (r == -1) {  
                    break;  
                }  
                // flip方法让缓冲区可以将新读入的数据写入另一个通道    
                buffer.flip();  
                byte[] content = new byte[buffer.limit()];
                buffer.get(content); 
                System.out.print(new String(content));  
                buffer.clear();
            }  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (in != null) {  
                try {  
                    in.close();  
                    
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
    
    
    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 = "D:\\example.txt";
        JavaIO.readFileByBytes(filename);
        JavaIO.readFileByChar(filename);
        JavaIO.readFileByLine(filename);
        JavaIO.readFileByRandomAccess(filename);
        JavaIO.readFileByBybeBuffer(filename);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值