您可以使用
ByteArrayOutputStream和
ByteArrayInputStream。例:
// A ByteArrayOutputStream holds the content in memoryByteArrayOutputStream outputStream = new ByteArrayOutputStream();// Do stuff with your OutputStream// To convert it to a byte[] - simply usefinal byte[] bytes = outputStream.toByteArray();// To convert bytes to an InputStream, use a ByteArrayInputStreamByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
您可以 对 其他 流对 执行相同操作。例如文件流:
// Create a FileOutputStreamFileOutputStream fos = new FileOutputStream("filename.txt");// Write contents to file// Always close the stream, preferably in a try-with-resources blockfos.close();// The, convert the file contents to an input streamfinal InputStream fileInputStream = new FileInputStream("filename.txt");而且,使用Spring MVC时,您绝对可以返回
byte[]包含您的文件的。只要确保您使用注释您的回复即可
@ResponseBody。像这样:
@ResponseBody@RequestMapping("/myurl/{filename:.*}")public byte[] serveFile(@PathVariable("file"} String file) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DbxEntry.File downloadedFile = client.getFile("/" + filename, null, outputStream); return outputStream.toByteArray();}


