这是您在 Java 端对其进行编码的方式:
在 Java 7 中使用 Google guava 的 com.google.common.io.BaseEncoding 和 com.google.common.io.Files:
byte[] data = BaseEncoding.base64().encode(bytes).getBytes();
Files.write(data, new File(outputFile));
在 Java 8 中使用 java.util.Base64 和 java.nio.file.Files/java.nio.file.Paths:
byte[] data = Base64.getEncoder().encode(bytes);
Files.write(Paths.get(outputFile), data);
并在节点端解码(同步版):
var fs = require("fs");
var buf fs.readFileSync("fromJava.dat");
var res = new Buffer(buf.toString(), "base64").toString("utf-8");
下面是调用 node.js 进程并证明正确性的相应 Java 端测试(对于 Java8 原生 java.util.Base64 和 Guava 的 com.google.common.io.BaseEncoding):
@Test
public void testJ8() throws IOException {
String input = "This is some UTF8 test data, which also includes some characters "
+ "outside the 0..255 range: ❊ ✓ ❦. Let's see how we get them to node and back";
byte[] data = Base64.getEncoder().encode(input.getBytes());
Files.write(Paths.get("fromJava.dat"), data);
Process p = Runtime.getRuntime().exec(new String[]{"node", "-e",
"console.log(new Buffer(require('fs').readFileSync('fromJava.dat').toString(), 'base64').toString('utf-8'))"});
assertEquals(input, new Scanner(p.getInputStream()).useDelimiter("\n").next());
}
试运行:
进程以退出代码 0 结束
@Test
public void testJ7() throws IOException {
String input = "This is some UTF8 test data, which also includes some characters "
+ "outside the 0..255 range: ❊ ✓ ❦. Let's see how we get them to node and back";
byte[] data = BaseEncoding.base64().encode(input.getBytes()).getBytes();
Files.write(data, new File("fromJava.dat"));
Process p = Runtime.getRuntime().exec(new String[]{"node", "-e",
"console.log(new Buffer(require('fs').readFileSync('fromJava.dat').toString(), 'base64').toString('utf-8'))"});
assertEquals(input, new Scanner(p.getInputStream()).useDelimiter("\n").next());
}
试运行:
进程以退出代码 0 结束
在 OSX/unix 上使用 Java 8 执行的两个测试,但这里使用的 Guava 19 与 Java 7 完全兼容,如果 node 可执行文件在 Windows 的路径上,那么没有理由不在那里运行测试(前提是它还可以在 -e 参数之后评估脚本,不知道)。