Base64 encode data: Difference between revisions
→{{header|Java}}
Line 1,178:
=={{header|Java}}==
<p>
Java offers the <code>Base64</code> class, which includes both the <code>Encoder</code> and <code>Decoder</code> classes.<br />
The implementation supports RFC 4648 and RFC 2045.
</p>
<p>
The usage is very simple, supply a <code>byte</code> array, and it will return, either an encoded <code>byte</code> array, or
an ISO 8859-1 encoded <code>String</code>.
</p>
import java.io.IOException;
import java.util.Base64;
<syntaxhighlight lang="java">
String encodeFile(String path) throws IOException {
try (FileInputStream stream = new FileInputStream(path)) {
}▼
}
</syntaxhighlight>
<p>
The result appears to be slightly different than some other language implementations, so I imagine the image has changed.<br />
It's a total of 20,116 bytes, so here's a shortened output.
</p>
<pre>
AAABAAMAMDAAAAEAIACoJQAANgAAACAgAAABACAAqBAAAN4lAAAQEAAAAQAgAGgEAACGNgAAKAAA
ADAAAABgAAAAAQAgAAAAAAAAJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
...
wv//AMH/hAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPw/AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQh
AAD8PwAA/D8AAIQhAACH4QAAh+EAAIQhAAD8PwAA/D8AAPw/AAA=
</pre>
<br />
Althernately<br />
Can also use org.apache.commons.codec.binary.Base64 from Apache Commons Codec
Line 1,252 ⟶ 1,286:
}
}</syntaxhighlight>
▲<syntaxhighlight lang="java">import java.nio.file.*;
▲import java.util.Base64;
▲ byte[] bytes = Files.readAllBytes(Paths.get("favicon.ico"));
▲ String result = Base64.getEncoder().encodeToString(bytes);
▲ }
▲}</syntaxhighlight>
<pre>AAABAAIAEBAAAAAAAABoBQ...QAAAAEAAAABAAAAAQAAAAE=</pre>
|