我已經用 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);
}
}
上面的代碼有兩種方法:
1- 將檔案編碼為 Base64 并將其寫入文本檔案
2- 解碼文本檔案并將其寫回新檔案
所有輸入/輸出檔案都在桌面上
我已經測驗過了并且這種編碼和解碼方法僅在 inputfile 是簡單文本檔案時才有效。如果輸入檔案是像本例那樣的影像或 zip 檔案,則解碼后的檔案將被破壞。你能解釋一下為什么它會這樣壞嗎?
無論如何,是否可以將任何型別的檔案普遍編碼為 Base64 并將其解碼?如果是,你可以調整上面的代碼來做到這一點嗎?
uj5u.com熱心網友回復:
您沒有關閉檔案。當您將文本(字串/讀取器/寫入器)用于二進制資料時,也存在上述問題:資料損壞、速度較慢、雙記憶體、不指定編碼時依賴于平臺。
最佳解決方案是不取記憶體中的位元組,另外制作一個 8/5 大的位元組陣列,基數為 64。
使用 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);
}
}
uj5u.com熱心網友回復:
在您的 decodeFile 方法中,您不應將 byte[] 轉換為字串。這將使用默認的平臺字符編碼,并且某些位元組在該編碼中可能沒有意義。相反,您應該直接在輸出檔案中寫入位元組陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/375390.html
