我的 DataInputStream 有问题,它没有完全读取文件,经常(每约 33000 个字符)跳过 2-3 个字符。我正在尝试将文件(8 mb)解析为 json,并且由于字符串中跳过的字符,我无法将字符串解析为 json。
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;
}
最佳答案
使用BufferedReader
而不是DataInputStream
。前者从字符输入流读取文本,缓冲字符以便提供字符、数组和行的高效读取。。出于性能问题,我更愿意使用 BufferedReader 而不是 Scanner。另外,使用 StringBuilder
而不是连接 String
。
这是一个启动示例:
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());
}
如果您使用 Java 6 或更早版本,则必须使用 System.getProperty("line.separator");
而不是 System.lineSeparator())
.
更多信息:
关于java - DataInputStream 是否会跳过字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25272863/