I would like to store some strings in a simple .txt file and then read them, but when I want to encode them using Base64 it doesn’t work anymore: it writes well but the reading doesn’t work. ^^
The write method:
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();
}
The read method :
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();
}
Any ideas why?
You have a couple of errors in your code.
First a couple of notes on your code:
*/but there is no one start-comment token.readmethod) is really bad idea unless you really know what you’re doing. What it does most of the time is hide the potential problems from you. At least write the stacktrace of an exception is acatchblock.Back to the solution:
Run the program. It throws an exception:
caused by line here:
inspecting the variable
tokensreveals that it has2elements, not3.So lets open the file generated by the
writemethod. Doing that shows this output:Note line breaking here. This is because the
Base64.encodeToString()appends additional newline at the end of the encoded string. To generate a one single line, without extra newlines, addBase64.NO_WRAPas the second parameter like this:Note here, you must delete file that was created earlier as it has improper line breaking.
Run the code again. It now creates a file with the proper contents:
Printing the output of
matrice_fullnow gives:Note that you’re not doing anything with the value in
decodevariable in your code, hence the second element is the Base64 representation of that value which is read from the file.