简体   繁体   English

使用 Base64 编码/解码 java 中的文件

[英]encode/decode file in java with Base64

I've written a encode/decode file in Java like below我在 Java 中编写了一个编码/解码文件,如下所示

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Test {
    
    public static void encodeFile(String inputfile, String outputfile) throws IOException {
        byte[] input_file = Files.readAllBytes(Paths.get(inputfile));
        byte[] encodedBytes = Base64.getEncoder().encode(input_file);
        String encodedString =  new String(encodedBytes);
        
        File ff =  new File(outputfile);
        FileOutputStream fileOut = new FileOutputStream(ff);
        OutputStreamWriter outStream = new OutputStreamWriter(fileOut);
        outStream.write(encodedString);
        outStream.flush();
    }
    
    public static void decodeFile(String encodedfilecontent, String decodedfile) throws IOException {   
        byte[] decoded = Base64.getDecoder().decode(encodedfilecontent);
        String decodedString =  new String(decoded);
        
        File ff =  new File(decodedfile);
        FileOutputStream fileOut = new FileOutputStream(ff);
        OutputStreamWriter outStream = new OutputStreamWriter(fileOut);
        outStream.write(decodedString);
        outStream.flush();
    }

    public static void main(String[] args) throws IOException {
        
        String inputfile = "C:\\Users\\John\\Desktop\\Files.zip";
        
        String outputfile = "C:\\Users\\John\\Desktop\\encoded.txt";
        
        encodeFile(inputfile, outputfile);
        
        String encodedfilecontent = new String(Files.readAllBytes(Paths.get(outputfile)));
        
        String decodedfile = "C:\\Users\\John\\Desktop\\DecodedFiles.zip";
        
        decodeFile(encodedfilecontent, decodedfile);

    }

}

The above code has 2 methods:上面的代码有2个方法:
1- To encode file to Base64 and write it in a text file 1-将文件编码为 Base64 并将其写入文本文件
2- To decode the text file and write it back into a new file 2-解码文本文件并将其写回新文件
All the input/output files are in desktop所有输入/输出文件都在桌面
I've test this and this encode and decode methods only work if inputfile is simple text file.我已经对此进行了测试,并且仅当 inputfile 是简单的文本文件时,此编码和解码方法才有效。 If the input file is an image or a zip file like this example, the decoded file will be broken.如果输入文件是图像或像本例这样的 zip 文件,则解码文件将被破坏。 Can you explain why it is broken like this?你能解释一下为什么它会这样坏吗?

Is there anyway to universally encode any type of file to Base64 and decode it back?无论如何,是否可以将任何类型的文件普遍编码为 Base64 并将其解码回来? If yes can you tweak the above code to do that?如果是,您可以调整上面的代码来做到这一点吗?

In your decodeFile method you should not convert the byte[] into a String.在您的 decodeFile 方法中,您不应将 byte[] 转换为字符串。 This will use the default platform character encoding and some bytes may not make sense in that encoding.这将使用默认的平台字符编码,并且某些字节在该编码中可能没有意义。 Instead, you should write the byte array in the output file directly.相反,您应该直接在 output 文件中写入字节数组。

You are not closing the files.您没有关闭文件。 Also there is the mentioned problem when you use text (String/Reader/Writer) for binary data: corrupt data, slower, double memory, platform dependent when not specifying the encoding.当您对二进制数据使用文本(字符串/读取器/写入器)时,还会出现上述问题:数据损坏、速度较慢、双 memory、在未指定编码时取决于平台。

The optimal solution is not to take the bytes in memory, additionally making a 8/5 larger byte array with base 64.最佳解决方案是不取 memory 中的字节,另外制作一个以 64 为基数的 8/5 大字节数组。

Use try-with-resources to automatically close the files, even on an exception (like illegal Base 64 chars).使用 try-with-resources 自动关闭文件,即使出现异常(如非法 Base 64 字符)。

public static void encodeFile(String inputFile, String outputFile)
        throws IOException {
    Path inPath = Paths.get(inputFile);
    Path outPath = Paths.get(outputFile);
    try (OutputStream out = Base64.getEncoder().wrap(Files.newOutputStream(outPath))) {
        Files.copy(inPath, out);
    }
}

public static void decodeFile(String encodedfilecontent, String decodedfile)
        throws IOException {
    Path inPath = Paths.get(encodedfilecontent);
    Path outPath = Paths.get(decodedfile);
    try (InputStream in = Base64.getDecoder().wrap(Files.newInputStream(inPath))) {
        Files.copy(in, outPath);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM