0

In order to do some testing I want to create an instance of FileInputStream from a String variable instead of reading from a file.
Basically when the FileInputStream reads bytes from a file, I want those bytes to come from a string variable instead of a file. Is there a way to maybe create a FileInputStream instance to read from a byteArray[] or some other way to make FileInputStream to read from a String variable instead from a file ?

Edit :
I am aware of how to create an InputStream from a String. My issue here is that the code I am testing uses a FileInputStream to read form an actual file so I need to create an instance of FileInputStream only.

Piece of code under test is :

final InputStream inputStream = new FileInputStream(inputFile);

Is there a way to modify this or use alternatives that would allow me to test it without having to read form an actual file ?

Duplicate
I have a distinct solution not implemented in any of the answers in the question that this question is marked duplicate of. The mediator has completely misjudged the whole question since none of those answers seem to work for me and the one that finally did work thanks to a suggestion by @Thilo, I cannot update here because of the duplicate stamp.

iammrmehul
  • 730
  • 1
  • 14
  • 35
  • 3
    No. But you can get a `ByteArrayInputStream` instead. Both implement the `InputStream` interface, so you can pass them on as such. – Thilo Jun 21 '19 at 08:15
  • 1
    If you are going to read text from this `InputStream` (as opposed to binary data), you may want to refactor to use a `Reader`. Then you can use `StringReader` directly (instead of `ByteArrayInputStream`) – Thilo Jun 21 '19 at 08:18
  • The issue is I want to test my code which is reading using a `FileInputStream` from a file but during testing I want `FileInputStream` to stream a `String` instead of a `File`. – iammrmehul Jun 21 '19 at 08:18
  • `new ByteArrayInputStream(theString.getBytes(characterSetYouWant))` or `new StringReader(theString)` – Thilo Jun 21 '19 at 08:20
  • Can I create a dummy `File` that streams a `String` ? – iammrmehul Jun 21 '19 at 08:22
  • 1
    You need a real `File` for a `FileInputStream`. Your test code could write a temporary file for that. But it seems much easier to change your class to work with `Reader` or `InputStream` instead. – Thilo Jun 21 '19 at 08:23
  • Have a look at `StringBufferInputStream`, and don't use `FileInputStream` where `InputStream` would do. – user207421 Jun 21 '19 at 09:45

0 Answers0