【问题标题】:How to avoid saving a file on hard drive?如何避免将文件保存在硬盘上?
【发布时间】:2015-12-28 07:06:59
【问题描述】:

每次我运行以下代码时,文件都会保存在硬盘上。但是,我希望它只保存在 Object Storage 容器中。

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

【问题讨论】:

  • 您使用的是哪个库?答案将取决于 API 支持什么。
  • 删除将其写入文件的 3 行代码(顺便说一句,这是错误的,因为它不会关闭流)?我们这里有什么遗漏吗?
  • 这取决于您使用的 API / 环境。一般来说,Java 有大量的内存写入器/读取器
  • @Peter Lawrey:我正在使用 import java.io.BufferedWriter;导入java.io.File;导入 java.io.FileWriter;
  • @Peter Lawrey:好的,抱歉。我正在使用这个 API:openstack4j.com

标签: java file file-io filewriter bufferedwriter


【解决方案1】:

通过读取 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));

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多