How to read and write Base64 file

In the other tutorial, you learned how to encrypt a String and

decode it again. Now we want to write an encoded text with Base64 tool.

This is similar like in the other Tutorial. Before you start encoding it, you have to consider creating a “UTF-8( Universal Coded Character Set )” based text. Add the following line before writing a text to a specific path:

String input = new String(stream,"UTF-8");

 public void writeFile(File ft){
        try {

           
            FileWriter ftw = new FileWriter(ft, true);
            BufferedWriter bw = new BufferedWriter(ftw);

            String sum = "Hello World";
            byte[] stream = android.util.Base64.encode(sum.getBytes(), Base64.DEFAULT);
            String input = new String(stream,"UTF-8");

            bw.write(input);

            bw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

}
    public String readFile(File ft){
        String name = "";
        BufferedReader br = null;
        String response = null;
       String decodedBase64 = null;
        try {
            FileInputStream fileInputStreamReader = new FileInputStream(ft);
            byte[] bytes = new byte[(int)ft.length()];
            fileInputStreamReader.read(bytes);
            decodedBase64 = new String(android.util.Base64.decode(bytes,Base64.DEFAULT));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        
        return decodedBase64;

    }

Leave a Reply