【问题标题】:On Android, how to read the exact text of a file, when one finishes with a newline, and another doesn't在 Android 上,如何读取文件的确切文本,当一个以换行符结束而另一个不以换行符结束时
【发布时间】: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


    【解决方案1】:

    你最好不要使用 readLine() 而是使用 read()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 2020-11-02
      • 2011-03-07
      相关资源
      最近更新 更多