Issue with java String and String Builder

不羁岁月 提交于 2019-12-08 07:14:54

问题


I'm working on a project in which I have to decrypt a xml text from PHP server and parse into java, I have decrypted the xml text by using CipherInputStream and seen xml file fully get printed, but I'm facing a weird issue while trying to store the xml text in a java string, I'm working on the code below:

public String decrypt(InputStream Fis){

Cipher c = Cipher.getInstance(algo + "/CBC/NoPadding");

String add = "";

StringBuilder getAns = new StringBuilder();

c.init(Cipher.DECRYPT_MODE, key);

CipherInputStream cis = new CipherInputStream(Fis , c);

byte[] encData = new byte[16];

int dummy;

while ((dummy = cis.read(encData)) != -1)
        {

            System.out.println(new String(encData, "UTF-8").trim()); 

                    add = (new String(encData, "UTF-8").trim());

                    getAns.append(add);


}

System.out.println(getAns); 
...
}

It prints the full XML text in log cat by the first println statement inside while loop, But when printing the StringBuilder getAns, it only prints a part of the text.

I have also tried just using String:

add = add + (new String(encData, "UTF-8").trim());

also using ArrayList<String> but it only prints a part of the text.

I guess this may be due to a silly mistake , but I'm struggling with this. Any help will be appreciated.


回答1:


You are reading some bytes from the input stream inside the while condition:

while ((dummy = cis.read(encData)) != -1)

This already populates the encData byte array with having the correct number of read bytes in the dummy variable. Afterwards you again read some bytes:

dummy = cis.read(encData);

This overwrites the bytes you have read one step before. Delete that line!




回答2:


Finally caught the issue, It's with the System.out.pritnln(), It has certain limits for printing. This function can only print around 4060 characters at a time, I've found this by using getAns.substring(10000,15000);.



来源:https://stackoverflow.com/questions/20628307/issue-with-java-string-and-string-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!