如何避免将文件保存在硬盘上?

How to avoid saving a file on hard drive?

每次我运行下面的代码,文件都保存在硬盘上。但是,我希望它只保存在对象存储容器中。

OSClient os = OSFactory.builder()
                .endpoint("...")
                .credentials("...","...")
                .tenantName("...")
                .authenticate();

        String containerName = "MyImgs";
        String objectName = "test.jpg";

BufferedWriter output = null;
        try {
            File f = new File(objectName);
            output = new BufferedWriter(new FileWriter(f));
            output.write(text);
            String etag = os.objectStorage().objects().put(containerName, 
                                                           objectName, 
                                                           Payloads.create(f));
        } catch ( IOException e ) {
            e.printStackTrace();
        }

更新: 我正在使用这个 API.

查看 Payloads 的 Javadoc,它有一个接受 InputStream 的方法。要将 String 作为 InputStream 读取,您可以这样做

Payloads.create(new ByteArrayInputStream(text.getBytes());

这将避免创建文件的需要,以便您可以阅读。

通过阅读 OpenStack4j API,可以从 InputStream 创建有效载荷,那么为什么不这样做而不是从 File 呢?

使用如下辅助函数将 text 转换为 InputStream

private static InputStream newInputStreamFrom(String text) {
    try {
        return new ByteArrayInputStream(text.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(); // should not occur
    }
}

然后您的代码可能如下所示:

OSClient os = OSFactory.builder()
            .endpoint("...")
            .credentials("...","...")
            .tenantName("...")
            .authenticate();

    String containerName = "MyImgs";
    String objectName = "test.jpg";
    InputStream stream = newInputStreamFrom(text);
    String etag = os.objectStorage().objects().put(containerName, 
                                                       objectName,
                                                       Payloads.create(stream));