maxivis
maxivis

Reputation: 1797

Writing multiple files with Spring Batch

I'm a newbie in Spring Batch, and I would appreciate some help to resolve this situation: I read some files with a MultiResourceItemReader, make some marshalling work, in the ItemProcessor I receive a String and return a Map<String, List<String>>, so my problem is that in the ItemWriter I should iterate the keys of the Map and for each one of them generate a new file containing the value associated with that key, can someone point me out in the right direction in order to create the files?
I'm also using a MultiResourceItemWriter because I need to generates files with a maximum of lines.
Thanks in advance

Upvotes: 4

Views: 3477

Answers (1)

maxivis
maxivis

Reputation: 1797

Well, finaly got a solution, I'm not really excited about it but it's working and I don't have much more time, so I've extended the MultiResourceItemWriter and redefined the "write" method, processing the map's elements and writing the files by myself. In case anyone out there needs it, here it is.

    @Override
    public void write(List items) throws Exception {

        for (Object o : items) {
                 //do some processing here

                 writeFile(anotherObject);
        }

    private void writeFile (AnotherObject anotherObject) throws IOException {
        File file = new File("name.xml");
        boolean restarted = file.exists();
        FileUtils.setUpOutputFile(file, restarted, true, true);

        StringBuffer sb = new StringBuffer();
        sb.append(xStream.toXML(anotherObject));

        FileOutputStream os = new FileOutputStream(file, true);

        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")));
        bufferedWriter.write(sb.toString());
        bufferedWriter.close();
    }

And that's it, I want to believe that there is a better option that I don't know, but for the moment this is my solution. If anyone knows how can I enhance my implementation, I'd like to know it.

Upvotes: 1

Related Questions