首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataInputStream是否跳过字符?

DataInputStream是否跳过字符?
EN

Stack Overflow用户
提问于 2014-08-12 19:48:13
回答 1查看 277关注 0票数 0

我对DataInputStream有一个问题,它不完整地读取文件-经常跳过2-3个字符(每33000个字符)。我试图将文件(8 mb)解析为json,对于字符串中跳过的字符,我不能将字符串解析为json。

代码语言:javascript
复制
public static String readTemplate(String templateName) throws IOException
{
    log.info("Opening Template");
    InputStream resStream = this.getClass().getResourceAsStream("/assets/"+SpellCraftMod.MODID+"/templates/"+templateName+".json"); // I need to open the file that way
    DataInputStream in = new DataInputStream(resStream);
    String temp = "";
    SpellCraftMod.log.info("Reading Data");
    int available = 0;
    while ((available = in.available()) > 0)
    {
        try
        {
            temp += in.readUTF();
        } catch (EOFException ignore) {}
        log.info("To GO: " + available);
    }
    log.info("Closing File");
    in.close();
    resStream.close();
    return temp;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-12 19:52:00

使用BufferedReader而不是DataInputStream。前者从字符输入流中读取文本,缓冲字符,以便有效地读取字符、数组和行。我更愿意在性能问题上使用BufferedReader而不是Scanner。另外,使用StringBuilder而不是连接String的。

下面是一个开球的例子:

代码语言:javascript
复制
BufferedReader br = new BufferedReader( new InputStreamReader(resStream, "UTF-8") );
StringBuilder sb = new StringBuilder();
String line;
while ( (line = br.readLine()) != null) {
    sb.append(line).append(System.lineSeparator());
}

如果您使用Java6或更高版本,那么您必须使用System.getProperty("line.separator");而不是System.lineSeparator())

更多信息:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25272863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档