StringBuffer如何工作?为什么这样做?

时间:2013-06-27 08:08:53

标签: java android

以下是我的代码:

        fis = openFileInput("MY_FILE");
        StringBuffer fileContent = new StringBuffer("");
        byte[] buffer = new byte[1024];
        while (fis.read(buffer) != -1) {
            fileContent.append(new String(buffer));
        }
        String myVariable = fileContent.toString().trim();

为什么StringBuffer需要字节?这究竟是如何工作的?

将myVariable设置为fileContent时,为什么数据后面会有额外的空格? (假设MY_FILE包含文本“dad”)

如果没有trim方法,它会将变量设置为: 爸爸


爸爸之后有很多空白。即使文本文件只是说“爸爸”

2 个答案:

答案 0 :(得分:4)

你得到空格,因为当你的文字是“爸爸”时,你的缓冲区大小是1024,这意味着缓冲区中有很多空的空间。

由于byte是原始数据类型,缓冲区中空白空间的内容不能为null,而是默认为0,将其转换为String时会被解释为空格。

答案 1 :(得分:2)

原因在于Raghav Sood的回答。您可以使用以下方法克服它:

byte[] buffer = new byte[1024];
int read = 0; // saves how many bytes were actually read
while ((read = fis.read(buffer)) != -1) {
    // don't use the complete buffer, only the used part of it.
    fileContent.append(new String(buffer, 0, read));
}
String myVariable = fileContent.toString();
相关问题