Pith
Pith

Reputation: 3794

Read objects in a file with Camel?

I have a file containing java objects, wrote with this code:

     from(somewhere).process(new Processor() {

          @Override
          public void process(final Exchange exchange) {
              ...
              ByteArrayOutputStream bos = new ByteArrayOutputStream();
              ObjectOutput out = new ObjectOutputStream(bos);
              out.writeObject(myObject);
              exchange.getOut().setBody(bos.toByteArray());
          }
     }).to("file://pathFile");

And now, I want read them fastly. I don't know how can I do that, something like the following code I gess.

from("file://pathFile").convertBodyTo(String.class)

.split(body().tokenize("???")) // How can I tokenize my file ?

.streaming().threads(2)

.process(new Processor() {

      @Override
      public void process(final Exchange exchange) {
        String filePath = (String) exchange.getIn().getHeader(Exchange.FILE_PATH);
        File file = new File(filePath);
        MyObject myObject = null;
        try {
          FileInputStream fis = new FileInputStream(file);
          InputStream buffer = new BufferedInputStream(fis);
          ObjectInput input = new ObjectInputStream(buffer);

          Object obj = null;
          while ((obj = input.readObject()) != null) {
              // Do something
              myObject = obj;
          }

        } catch (Exception e) {
            ...
        } finally {
          ...
        }
        exchange.getIn().setBody(myObject);
      }
}).to(somewhere);

EDIT: I edit my way to read object. There is still a problem with that code, we can't append to an ObjectOutputStream. That will corrupt the stream. There is a solution [here] for this problem. We can only write the stream header one time.

But If I do that, I wont be able to split and read my file with multiple threads. So can I split or access my file on ObjectOutputStream header ?

Upvotes: 1

Views: 1199

Answers (1)

Ben ODay
Ben ODay

Reputation: 21005

you just converted it to a String using convertBodyTo(String.class), therefore you have a String in the body rather than an InputStream....

Upvotes: 1

Related Questions