有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Wicket中iresourcestream的java字节[]

我想实现this page的示例

我被getResourceStream()方法卡住了。我的应用程序有一个byte[](生成的XML文件),用户应该可以下载。问题是我不知道如何将byte[]转换为IResourceStream

这就是我所拥有的:

final AJAXDownload download = new AJAXDownload()
{
    private static final long serialVersionUID = 1L;

    @Override
    protected IResourceStream getResourceStream()
    {
        ByteArrayResource bar = new ByteArrayResource("TEXT??", xmlFileInBytes);
                return (IResourceStream) bar;
        }
    };

上面的代码给出了一个ClassCastException。有人能解释一下我如何解决这个问题吗


共 (3) 个答案

  1. # 1 楼答案

    您可以使用IResourceStream的子类StringResourceStream,并使用字节数组:

    你可以这样做:

      byte byteArray[] = new byte[1024]   //this is the byte array containing the xml which you want to use.
      StringResourceStream srs = new StringResourceStream(new String(byteArray));
    

    因此,在您的情况下,方法如下所示:

     final AJAXDownload download = new AJAXDownload()
     {
         private static final long serialVersionUID = 1L;
    
         @Override
         protected IResourceStream getResourceStream()
         {
             StringResourceStream bar = new StringResourceStream (new String(xmlFileInBytes) );
                     return (IResourceStream) bar;
             }
         };
    
  2. # 2 楼答案

    ByteArrayResource实现了IResource,但没有IResourceStream。这就是为什么你有ClassCastException

    要解决这个问题,您应该找到一个实现IResourceStream的类;有关可能实现的列表,请参见Javadoc

  3. # 3 楼答案

    目前这是未经测试的代码,但不是

    ByteArrayResource bar = new ByteArrayResource("TEXT??", xmlFileInBytes);
    return (IResourceStream) bar;
    

    您可以按如下方式尝试^{}

    ByteArrayResource bar = new ByteArrayResource("TEXT??", xmlFileInBytes);
    return bar.getResourceStream();