InputStream (@NotNull VirtualFile file, @NotNull InputStream nativeStream, long fileLength, boolean readOnly) { if (nativeStream instanceof BufferExposingByteArrayInputStream byteStream) { // optimization byte[] bytes = byteStream.getInternalBuffer(); storeContentToStorage(fileLength, file, readOnly, bytes, bytes.length); return nativeStream; } BufferExposingByteArrayOutputStream cache = new BufferExposingByteArrayOutputStream((int)fileLength); return new ReplicatorInputStream(nativeStream, cache) { boolean isClosed; @Override public void close() throws IOException { if (!isClosed) { try { boolean isEndOfFileReached; try { isEndOfFileReached = available() < 0 || read() == -1; } catch (IOException ignored) { isEndOfFileReached = false; } super.close(); if (isEndOfFileReached) { storeContentToStorage(fileLength, file, readOnly, cache.getInternalBuffer(), cache.size()); } } finally { isClosed = true; } } } }; }