Converting file into Base64String and back again

后端 未结 2 1990
心在旅途
心在旅途 2020-11-27 11:10

The title says it all:

  1. I read in a tar.gz archive like so
  2. break the file into an array of bytes
  3. Convert those bytes into a Base64 string
相关标签:
2条回答
  • 2020-11-27 11:53

    If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this

    Byte[] bytes = File.ReadAllBytes("path");
    String file = Convert.ToBase64String(bytes);
    

    And correspondingly, read back to file:

    Byte[] bytes = Convert.FromBase64String(b64Str);
    File.WriteAllBytes(path, bytes);
    
    0 讨论(0)
  • 2020-11-27 11:54
    private String encodeFileToBase64Binary(File file){    
    String encodedfile = null;  
    try {  
        FileInputStream fileInputStreamReader = new FileInputStream(file);  
        byte[] bytes = new byte[(int)file.length()];
        fileInputStreamReader.read(bytes);  
        encodedfile = Base64.encodeBase64(bytes).toString();  
    } catch (FileNotFoundException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    } catch (IOException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }  
        return encodedfile;  
    }
    
    0 讨论(0)
提交回复
热议问题