如何在Java中模拟文件IO

如何在Java中模拟文件IO

本文介绍了如何在Java中模拟文件IO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个类 MockFile 模仿 java.io.File w.r.t.文件读写?我使用到处都是我自己的方法而不是 new FileInputStream(....) new FileOutputStream(....),所以这部分是没有问题的(我总是委托给适当的流)。非trivila部分是在更复杂的情况下执行我的 MockFileInputStream MockFileOutputStream

How can I create a class MockFile mimicking java.io.File w.r.t. file read and write? I using everywhere my own methods instead of new FileInputStream(....) and new FileOutputStream(....), so this part is no problem (I always delegate to the appropriate stream). The non-trivila part is the implementation of my MockFileInputStream and MockFileOutputStream in more complicated cases.

没有问题,当我第一次写入文件然后读取它时,我可以简单地使用 ByteArrayOutputStream 等等。这很简单,但是交织读取和写入不能工作。任何比写自己的版本 ByteArrayOutputStream

There's is no problem, when I first write to a file and then read it, I can simply use a ByteArrayOutputStream and so on. That's simple, but with interleaving reads and writes it can't work. Any better idea than writing my own version of ByteArrayOutputStream?

推荐答案

会使用一个真实的文件和一个真正的 FileInputStream FileOutputStream 。否则,你只是在测试代码:毫无意义。

I would use a real file and a real FileInputStream and FileOutputStream. Otherwise you're just exercising test code: pretty pointless really.

这篇关于如何在Java中模拟文件IO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:17