Java IO读写文件总结——文件随机读写,顺序读写!

顺序IO和随机IO

对于磁盘的读写分为两种模式,顺序IO和随机IO。 随机IO存在一个寻址的过程,所以效率比较低。而顺序IO,相当于有一个物理索引,在读取的时候不需要寻找地址,效率很高。

网上盗了一个图(侵权删)

Java中的随机读写

在Java中读写文件的方式有很多种,先总结以下3种方法:

 FileWriter和FileReader

public static void fileWrite(String filePath, String content) {
            File file = new File(filePath);
            //创建FileWriter对象
            FileWriter writer = null;
            try {
                 //如果文件不存在,创建文件
                 if (!file.exists())
                      file.createNewFile();
                 writer = new FileWriter(file);
                 writer.write(content);//写入内容
                 writer.flush();
                 writer.close();
            } catch (IOException e) {
                 e.printStackTrace();
            }
       }
          
       public static void fileRead(String filePath) {
            File file = new File(filePath);
            if (file.exists()) {
                 try {
                      //创建FileReader对象,读取文件中的内容
                      FileReader reader = new FileReader(file);
                      char[] ch = new char[1];
                      while (reader.read(ch) != -1) {
                           System.out.print(ch);
                      }
                      reader.close();
                 } catch (IOException ex) {
                      ex.printStackTrace();
                 }
                    
            }
       } 

BufferedReader和BufferedWriter BufferedReader和BufferedWriter与FileWriter和FileReader代码的写法一致,Buffer也多了一个读取一行字符的操作。

  public class BuffredRWHelper {
       public static void fileWrite(String filePath, String content) {
            File file = new File(filePath);
            //创建FileWriter对象
            BufferedWriter writer = null;
            try {
                 //如果文件不存在,创建文件
                 if (!file.exists())
                      file.createNewFile();
                 writer = new BufferedWriter(new FileWriter(file));
                 writer.write(content);//写入内容
                 writer.flush();
                 writer.close();
            } catch (IOException e) {
                 e.printStackTrace();
            }
       }
          
       public static void fileRead(String filePath) {
            File file = new File(filePath);
            if (file.exists()) {
                 try {
                      //创建FileReader对象,读取文件中的内容
                      BufferedReader reader = new BufferedReader(new FileReader(file));
                      String line;
                      while ((line = reader.readLine()) != null) {
                           System.out.print(line);
                      }
                      reader.close();
                 } catch (IOException ex) {
                      ex.printStackTrace();
                 }
                    
            }
       }
  } 

FileInputStream和FileOutputStream 使用Stream的形式是最原始的方式,以字节数组为中间的中转缓解

public static void fileWrite(String filePath, String content) {
     FileOutputStream outputStream = null;
     try {
         File file = new File(filePath);
         boolean isCreate = file.createNewFile();//创建文件
         if (isCreate) {
             outputStream = new FileOutputStream(file);//形参里面可追加true参数,表示在原有文件末尾追加信息
             outputStream.write(content.getBytes());
         }else {
             outputStream = new FileOutputStream(file,true);//表示在原有文件末尾追加信息
             outputStream.write(content.getBytes());
         }
     } catch (Exception e) {
         e.printStackTrace();
     } finally {
         try {
             outputStream.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }
	
 public static void fileRead(String filePath) {
     File file = new File(filePath);
     if (file.exists()) {
         try {
             //创建FileInputStream对象,读取文件内容
             FileInputStream fis = new FileInputStream(file);
             byte[] bys = new byte[1024];
             while (fis.read(bys, 0, bys.length) != -1) {
                 //将字节数组转换为字符串
                 System.out.print(new String(bys, StandardCharsets.UTF_8));
             }
         } catch (IOException ex) {
             ex.printStackTrace();
         }
			
     }
 } 

Java中的顺序读写

上面的对文件的读写都是随机读写,如果用来写比较小的日志文件还能满足要求,如果用来操作一个文件的读写,那可能带来很大的性能消耗。

顺序IO的读写在中间件使用的很频繁,尤其是在队列中。几乎所有的队列(kafka,qmq等使用文件存储消息)都采用了顺序IO读写。

与随机读写不同的是,顺序读写是优先分配一块文件空间,然后后续内容追加到对应空间内。

在使用顺序IO进行文件读写时候,需要知道上次写入的地方,所以需要维护一个索引或者轮询获得一个没有写入位置。

public static long fileWrite(String filePath, String content, int index) {
     File file = new File(filePath);
     RandomAccessFile randomAccessTargetFile;
     MappedByteBuffer map;
     try {
          randomAccessTargetFile = new RandomAccessFile(file, "rw");
          FileChannel targetFileChannel = randomAccessTargetFile.getChannel();
          map = targetFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, (long) 1024 * 1024 * 1024);
          map.position(index);
          map.put(content.getBytes());
          return map.position();
     } catch (IOException e) {
          e.printStackTrace();
     } finally {
     }
     return 0L;
}

public static String fileRead(String filePath, long index) {
     File file = new File(filePath);
     RandomAccessFile randomAccessTargetFile;
     MappedByteBuffer map;
     try {
          randomAccessTargetFile = new RandomAccessFile(file, "rw");
          FileChannel targetFileChannel = randomAccessTargetFile.getChannel();
          map = targetFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, index);
          byte[] byteArr = new byte[10 * 1024];
          map.get(byteArr, 0, (int) index);
          return new String(byteArr);
     } catch (IOException e) {
          e.printStackTrace();
     } finally {
     }
     return "";
}

文件合并方法:

/**
     * 文件合并
     */
    public static void mergeFile(List<String> inputPaths, String outputPath) throws FileNotFoundException {

        Vector<InputStream> inputStream = new Vector<InputStream>();

        if (CollectionUtils.isEmpty(inputPaths)) {
            throw new LogicException("合并文件路径不能为空");
        }

        for (String inputPath : inputPaths) {
            InputStream in = new  FileInputStream(new File(inputPath));
            inputStream.add(in);
        }

        //构造一个合并流
        SequenceInputStream stream = new SequenceInputStream(inputStream.elements());
        BufferedOutputStream bos = null;
        try {
             bos = new BufferedOutputStream(
                    new FileOutputStream(outputPath));

            byte[] bytes = new byte[10240];
            int len = -1;
            while((len=stream.read(bytes))!=-1){
                bos.write(bytes,0,len);
                bos.flush();
            }
            log.info("文件合并完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != bos ) {
                    bos.close();
                }
                stream.close();
            } catch (IOException ignored) {
            }
        }
    }

 

  • 5
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 17
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangkaixuan456

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值