1

I have a an InputStream as a parameter, which works just fine when I read it for the first time, however, reading the same InputStream doesn't work. I just can't get mark() and reset()to work. Anyone know how to reset this? I'm reading a .txt file. The file contains spawn values for enemy objects that don't reappear, since the inputstream mark(?) is at the end, I guess?

readTxt(InputStream resource){
//resource is a .txt as ResourceStream
arrayList = new BufferedReader(new InputStreamReader(resource,
                StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
Ryan Sangha
  • 442
  • 6
  • 17
  • Why don't you store values at first read ? explain more, store nameFile and stream twice not possible ? – azro May 14 '18 at 13:33

2 Answers2

5

mark() only work if the input stream supported it (you can check by markSupported().

It does not work for every stream.

One way to read the input stream is to copy content of input stream to an array and re-read the array:

byte[] buffer = new byte[2048];

ByteArrayOutputStream output = new ByteArrayOutputStream();

int byteCount;
while ((byteCount = inputStream.read(buffer)) != -1)
{
    output.write(buffer, 0, byteCount);
}
byte[] source = output.toByteArray();

// Now you have ability to reread the "secondary" input stream:
InputStream is = new ByteArrayInputStream(source); 
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
2

Since the InputStream was markSupported(), I could use the mark()and reset().

//mark 0, before you start reading your file
inputStream.mark(0);


//read your InputStream here
read(inputStream)...

//reset the stream, so it's ready to be read from the start again. 
inputStream.reset();
Ryan Sangha
  • 442
  • 6
  • 17
  • Do you know of a way to read the stream if it's been read internally. I don't receive it in my code until after Spring already called read function. Is it possible? – wheeleruniverse Nov 06 '18 at 21:37