[erlang-questions] Jinterface: communication between Java and Erlang using system file

Alain O'Dea <>
Fri Mar 18 16:14:01 CET 2011


Hi Robby:

On 2011-03-18, at 7:45, Robert Raschke <> wrote:

> Hi Zab,
> 
> On Thu, Mar 17, 2011 at 9:02 PM, Zabrane Mickael <> wrote:
> 
>> Hi guys,
>> 
>> Please, have a look to the following simple Java code
>> which try to encode a simple Erlang tuple and save it to disk.
>> 
>> -8-8-8-8-8-8-8-8-8-8 snip -8-8-8-8-8-8-8-8-8-8
>> 
>> // encode a simple Erlang tuple {ok, "Hello World"}
>> OtpErlangObject[] reply = new OtpErlangObject[2];
>> reply[0] = new OtpErlangAtom("ok");
>> reply[1] = new OtpErlangBinary("Hello World!");
>> OtpErlangTuple tuple = new OtpErlangTuple(reply);
>> 
>> // create an OtpOutputStream object from the binary
>> OtpErlangBinary binary = new OtpErlangBinary(tuple);
>> OtpOutputStream oos = new OtpOutputStream(binary);
>> 
>> oos.writeTo(fos);
>> 
>> // write the Erlang binary term to a file
>> File f = new File ("a.txt");
>> FileOutputStream fos = new FileOutputStream(f);
>> 
>> fos.flush();
>> fos.close();
>> 
>> -8-8-8-8-8-8-8-8-8-8 snip -8-8-8-8-8-8-8-8-8-8
>> 
>> When trying to read it from disk, I got an exception:
>> $ erl
>> 1> {ok, Bin} = file:read_file("a.txt").
>> {ok,<<109,0,0,2,17,172,237,0,5,115,114,0,38,99,111,109,
>>     46,101,114,105,99,115,115,111,110,46,111,...>>}
>> 2> binary_to_term(Bin).
>> ** exception error: bad argument
>>    in function  binary_to_term/1
>>       called as
>> binary_to_term(<<109,0,0,2,17,172,237,0,5,115,114,0,38,99,111,109,46,
>> 
>> 101,114,105,99,115,115,111,110,46,111,116,...>>)
>> 
>> 
>> What am I doing wrong?
>> Help appreciated ...
>> 
>> Regards,
>> Zab
>> 
>> 
> I haven't done much Java file writing/reading for a long time, so I've
> forgotten a lot.
> 
> But is it possible that the file gets written in "text" mode? And the IO
> system helpfully translates line ending characters for you?

Java's FileOutputStream writes raw bytes.  What you write is what you get.  You use wrapper classes like PrintWriter to write text.

There may be more packaging or initialization required to use OtpOutputStream in a way that binary_to_term can work with the output.

> 
> Since you're writing binary data, it's always a good idea to make sure
> you're writing to a binary file.
> 
> If I remember correctly the Erlang file module functions assume binary by
> default. Not sure about Java tho'.
> 
> Robby


More information about the erlang-questions mailing list