Object Storage - Error when reading text file

153 views Asked by At

When trying to read the content of a text file I received the error message "java.lang.ClassCastException: org.openstack4j.openstack.common.DLPayloadEntity incompatible with java.io.File".

How can I read the text file without writing it into a new file?

I tried to convert the file directly into String by using Apache Commons/ IO library's 'readFiletoString()' method:

public String test() {
    ObjectStorageDAO os;
    List<String> containers = null;
    String str = null;
    try {
        os = new ObjectStorageDAO(auth_url, userId, password, project, domainName);
        // List the containers
        containers = os.containers();
        SwiftObject so = os.getObject("MyContainer", "message.txt");
        File file = (File) so.download();
        str = FileUtils.readFileToString(file, "UTF-8");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        str = e.toString();
    }
    return str;

}
1

There are 1 answers

1
fabfas On BEST ANSWER

In short, you're getting class cast exception because you try to cast an Object of one data type (i.e. DLPayloadEntity) to another (i.e. File).

    SwiftObject so = os.getObject("MyContainer", "message.txt");
    DLPayloadEntity payload = so.download();

With "payload" object, you can retrieve the response following ways;

  • getHttpResponse()
  • getInputStream()
  • writeToFile(File file)

You can do the following to retrieve the text;

InputStream stream = payload.getInputStream();

"stream" object allows you to read bytes.