2016-12-28 40 views
0

尝试读取文本文件的内容时收到错误消息“java.lang.ClassCastException:org.openstack4j.openstack.common.DLPayloadEntity incompatible with java.io.File” 。对象存储 - 读取文本文件时出错

如何在不写入新文件的情况下读取文本文件?

我试着将文件直接通过使用Apache下议院/ IO库的“readFiletoString()方法转换成字符串:

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; 

} 

回答

2

总之,你得到类转换异常,因为你尝试施放一个数据类型的对象(即DLPayloadEntity)到另一个(即文件)。

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

对于“payload”对象,您可以按照以下方式检索响应;

  • getHttpResponse()
  • 的getInputStream()
  • 将writeToFile(档案文件)

您可以执行以下操作来检索的文本;

InputStream stream = payload.getInputStream(); 

“流”对象允许您读取字节。

+0

将该文件作为InputStream读取并将其转换为String解决了问题。 我将try-block改为 尝试{os = new DictionaryDAO(auth_url,userId,password,project,domainName); \t \t \t //列出容器 \t \t \t containers = os.containers(); \t \t \t SwiftObject so = os.getObject(“SpellChecking”,“english.dic”); \t \t \t DLPayload file = so.download(); \t \t \t str = getStringFromInputStream(file.getInputStream()); \t \t \t \t \t \t \t \t} https://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ –