1

我想将一些字符串存储在一个简单的 .txt 文件中,然后读取它们,但是当我想使用 Base64 对它们进行编码时,它不再起作用:它写得很好,但读取不起作用。^^

写法:

private void write() throws IOException {
    String fileName = "/mnt/sdcard/test.txt";
    File myFile = new File(fileName);

    BufferedWriter bW = new BufferedWriter(new FileWriter(myFile, true));

    // Write the string to the file
    String test = "http://google.fr";
    test = Base64.encodeToString(test.getBytes(), Base64.DEFAULT);

    bW.write("here it comes"); 
    bW.write(";");
    bW.write(test);
    bW.write(";");

    bW.write("done");
    bW.write("\r\n");

    // save and close
    bW.flush();
    bW.close();
}

读取方法:

private void read() throws IOException {
    String fileName = "/mnt/sdcard/test.txt";
    File myFile = new File(fileName);
    FileInputStream fIn = new FileInputStream(myFile);

    BufferedReader inBuff = new BufferedReader(new InputStreamReader(fIn));
    String line = inBuff.readLine();
    int i = 0;
    ArrayList<List<String>> matrice_full = new ArrayList<List<String>>();
    while (line != null) {
        matrice_full.add(new ArrayList<String>());
        String[] tokens = line.split(";");

        String decode = tokens[1];
        decode = new String(Base64.decode(decode, Base64.DEFAULT));

        matrice_full.get(i).add(tokens[0]);
        matrice_full.get(i).add(tokens[1]);
        matrice_full.get(i).add(tokens[2]);
        line = inBuff.readLine();
        i++;
    }
    inBuff.close();
}

任何想法为什么?

4

1 回答 1

4

您的代码中有几个错误。

首先对您的代码有几点说明:

  1. 在此处发布时,附加SSCCE有助于其他人调试您的代码。这不是 SSCEE,因为它不能编译。它缺少几个定义的变量,所以你必须猜出你的真正意思。此外,您在代码中粘贴了关闭评论标记:*/但没有一个开始评论标记。
  2. 除非您真的知道自己在做什么,否则捕获并仅抑制异常(例如在read方法中的 catch-block 中)确实是个坏主意。它大部分时间所做的就是向您隐藏潜在的问题。至少写一个异常的stacktrace是一个catch块。
  3. 为什么不直接调试它,检查输出到目标文件的确切内容?您应该学习如何做到这一点,因为这将加快您的开发过程,尤其是对于具有难以发现的问题的大型项目。

回到解决方案:

  1. 运行程序。它抛出一个异常:

    02-01 17:18:58.171: E/AndroidRuntime(24417): Caused by: java.lang.ArrayIndexOutOfBoundsException
    

    由此处的行引起:

    matrice_full.get(i).add(tokens[2]);
    

    检查变量tokens表明它具有2元素,而不是3.

  2. 因此,让我们打开该write方法生成的文件。这样做会显示此输出:

    here it comes;aHR0cDovL2dvb2dsZS5mcg==
    ;done
    here it comes;aHR0cDovL2dvb2dsZS5mcg==
    ;done
    here it comes;aHR0cDovL2dvb2dsZS5mcg==
    ;done
    

    注意这里的换行。这是因为Base64.encodeToString()在编码字符串的末尾附加了额外的换行符。要生成单行,而不需要额外的换行符,请添加Base64.NO_WRAP为第二个参数,如下所示:

    test = Base64.encodeToString(test.getBytes(), Base64.NO_WRAP);
    

    请注意,您必须删除之前创建的文件,因为它具有不正确的换行符。

  3. 再次运行代码。它现在创建一个具有正确内容的文件:

    here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
    here it comes;aHR0cDovL2dvb2dsZS5mcg==;done
    
  4. 打印matrice_fullnow 的输出给出:

    [
        [here it comes, aHR0cDovL2dvb2dsZS5mcg==, done],
        [here it comes, aHR0cDovL2dvb2dsZS5mcg==, done]
    ]
    

    请注意,您没有decode对代码中的变量值做任何事情,因此第二个元素是从文件中读取的该值的 Base64 表示。

于 2013-02-01T16:27:02.557 回答