ResourceLocatorItemStreamWriter extends AbstractResourceLocatorItemStream<S, T> implements ItemStreamWriter<T>, ResourceAwareItemStreamWriter<T> { @Override public void write(List<? extends T> items) throws Exception { Map<Resource, List<T>> splitMap = new HashMap<>(); if (resourceContext.containsResource()) { splitMap.put(resourceContext.getResource(), new ArrayList<>()); } for (T item : items) { resourceLocator.onWrite(item, resourceContext); if (resourceContext.hasChanged()) { splitMap.put(resourceContext.consumeResource(), new ArrayList<>()); } if (splitMap.containsKey(resourceContext.getResource())) { splitMap.get(resourceContext.getResource()).add(item); } } for (Map.Entry<Resource, List<T>> entry : splitMap.entrySet()) { Resource resource = entry.getKey(); List<T> subItems = entry.getValue(); delegate.setResource(resource); if (!opened) { delegate.open(resourceContext.getExecutionContext()); opened = true; } delegate.write(subItems); if (splitMap.size() > 1) { delegate.close(); delegate.update(resourceContext.getExecutionContext()); opened = false; } } }  @Override void write(List<? extends T> items);  }
@Test public void testWrite() throws Exception { ExecutionContext executionContext = new ExecutionContext(); delegator.setResourceLocator(new CountingItemResourceLocator<String>() { @Override public void onWrite(String item, ResourceContext context) throws ItemStreamException { context.changeResource(new FileSystemResource(item)); } }); delegator.open(executionContext); delegator.write(Arrays.asList("a", "b", "c")); delegator.update(executionContext); try { Assert.assertEquals("c", delegate.getResource().getFile().getPath()); } catch (IOException e) { Assert.fail(e.getMessage()); } delegator.close(); }