【发布时间】:2016-02-03 00:12:28
【问题描述】:
这与我发现自己在 Android 上的 Unity 中保存文本文件,然后在原生 Android 中读取它们的情况有关。
我们读取的文件之一是使用代码创建的 HMACMD5 签名,
byte[] bData = System.Text.Encoding.UTF8.GetBytes (data);
byte[] bKey = System.Text.Encoding.UTF8.GetBytes (key);
using (HMACMD5 hmac = new HMACMD5(bKey)) {
byte[] signature = hmac.ComputeHash (bData);
return System.Convert.ToBase64String (signature);
}
然后写到手机上用,
public static void SaveText (string path, string data) {
using (FileStream fs = new FileStream(path, FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(fs)) {
sw.Write (data);
}
}
}
我们要保存的另一个字符串是 JSON 字符串转储。签名在字符串末尾有一个换行符,但 JSON 字符串没有。我知道我可以手动添加一个,但这个问题是关于读取准确的文件内容。
在 Android 上,根据之前的 SO 答案,我阅读了文件,
String readFile(File file) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
br.close();
}
catch (IOException e) {
MyLogger.e(LOG_TAG, "Error opening file " + file.getPath(), e);
}
return text.toString();
}
我在每一行之后手动添加换行符,但如果我这样做,我无法准确读取 JSON 文件,该文件末尾没有换行符。如果我不添加换行符,我就没有准确地读取签名文件。
【问题讨论】:
标签: android json string unity3d newline