2011-01-28 47 views
4

我試過Swizzle Stream庫來替換輸入流中的令牌。使用Swizzle Stream替換流中的字符串

String RESOURCE_PATH = "FakePom.xml"; 
    InputStream pomIS = JarFinderServlet.class.getClassLoader().getResourceAsStream(RESOURCE_PATH); 

    if(null == pomIS) 
    throw new MavenhoeException("Can't read fake pom template - getResourceAsStream(RESOURCE_PATH) == null"); 

    Map map = ArrayUtils.toMap( new String[][]{ 
    {"@[email protected]", artifactInfo.getGroup() }, 
    {"@[email protected]", artifactInfo.getName() }, 
    {"@[email protected]", artifactInfo.getVersion() }, 
    {"@[email protected]", artifactInfo.getPackaging() }, 
    {"@[email protected]", artifactInfo.getFileName() }, 
    {"@[email protected]", req.getQueryString() }, 
    }); 


    // This does not replace anything, no idea why. // 
    ReplaceStringsInputStream replacingIS = new ReplaceStringsInputStream(pomIS, map); 
    ReplaceStringInputStream replacingIS2 = new ReplaceStringInputStream(pomIS, "@[email protected]", "0.0-AAAAA"); 
    ReplaceStringInputStream replacingIS3 = new ReplaceStringInputStream(pomIS, "@", "#"); 

    ServletOutputStream os = resp.getOutputStream(); 
    IOUtils.copy(replacingIS, os); 
    replacingIS.close(); 

這沒有奏效。它只是不能取代。所以我訴諸於「PHP方式」...

String pomTemplate = IOUtils.toString(pomIS) 
    .replace("@[email protected]", artifactInfo.getGroup()) 
    .replace("@[email protected]", artifactInfo.getName()) 
    .replace("@[email protected]", artifactInfo.getVersion()) 
    .replace("@[email protected]", artifactInfo.getPackaging()) 
    .replace("@[email protected]", artifactInfo.getFileName()) 
    .replace("@[email protected]", req.getQueryString()); 

    ServletOutputStream os = resp.getOutputStream(); 
    IOUtils.copy(new StringInputStream(pomTemplate), os); 
    os.close(); 

作品。

怎麼了?

+0

代碼看起來不錯,可能是時候踏進去與調試。 – Ron 2011-01-28 15:26:11

回答

3

IOUtils.copy調用read(byte [])方法而不是read(),該方法被FixedTokenReplacementInputStream(ReplaceStringInputStream的超類)覆蓋。 你應該實現你自己的拷貝,例如,如下:

try { 
int b; 
while ((b = pomIS.read()) != -1) { 
    os.write(b); 
}} finally { os.flush();os.close(); } 
+0

哦...所以Swizzle有不一致的API,那是:)謝謝指出,這真的沒有跨過我的腦海。 – 2011-04-12 22:25:06