voltage

b64-cheatsheet

Sep 24th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. /**
  2.      * @param finPath  where to read binary data from
  3.      * @param foutPath where to write encoded data. if null, please create and use temporary file.
  4.      * @return file to read encoded data from
  5.      * @throws IOException is case of input/output errors
  6.      */
  7.     @NotNull
  8.     public File encodeFile(@NotNull String finPath, @Nullable String foutPath) throws IOException {
  9.         final File fin = new File(finPath);
  10.         final File fout;
  11.  
  12.         if (foutPath != null) {
  13.             fout = new File(foutPath);
  14.         } else {
  15.             fout = File.createTempFile("based_file_", ".txt");
  16.             fout.deleteOnExit();
  17.         }
  18.  
  19.         try (
  20.                 final FileInputStream fis = new FileInputStream(fin);
  21.                 final FileOutputStream fos = new FileOutputStream(fout);
  22.         ) {
  23.             while(true) {
  24.                 int b1 = fis.read();
  25.                 int b2 = fis.read();
  26.                 int b3 = fis.read();
  27.  
  28.                 if (b1 == -1) {
  29.                     break;
  30.                 }
  31.                 fos.write(toBase64[b1 >> 2]);
  32.                 if (b2 != -1) {
  33.                     fos.write(toBase64[((b1 & 3) << 4) | (b2 >> 4)]);
  34.                 } else {
  35.                     fos.write(toBase64[((b1 & 3) << 4)]);
  36.                     fos.write("==".getBytes());
  37.                     break;
  38.                 }
  39.                 if (b3 != -1) {
  40.                     fos.write(toBase64[((b2 & 15) << 2) | (b3 >> 6)]);
  41.                 } else {
  42.                     fos.write(toBase64[((b2 & 15) << 2)]);
  43.                     fos.write('=');
  44.                     break;
  45.                 }
  46.                 fos.write(toBase64[b3 & 63]);
  47.             }
  48.         }
  49.  
  50.         return fout;
  51.     }
Advertisement
Add Comment
Please, Sign In to add comment