我有我想要写入保存在我的 Java 程序中的字符串中的文件的内容。我需要将它们写入.txt
文件,然后将它们压缩到.gz
存档中。我能够做到这一切,但是当我从.gz
档案中提取文件时,提取的文件不再是.txt
文件扩展名。
这是我下面的代码:
private void fillFileBody(OutputStream outputStream) throws IOException {
Scanner scanner = new Scanner(new ByteArrayInputStream(this.fileBody.getBytes()));
while(scanner.hasNextLine()){
outputStream.write((scanner.nextLine() + "\n").getBytes());
}
scanner.close();
}
public void writeFileContentsToDisk(){
GZIPOutputStream gZipOutStream = null;
FileOutputStream initialTxtFileOutStream = null;
FileInputStream initialTxtFileInStream = null;
String txtFile = this.fileName + ".txt";
try {
initialTxtFileOutStream = new FileOutputStream(txtFile);
initialTxtFileOutStream.write((this.fileHeader).getBytes());
fillFileBody(initialTxtFileOutStream);
initialTxtFileOutStream.write(this.fileTrailer.getBytes());
initialTxtFileInStream = new FileInputStream(txtFile);
gZipOutStream = new GZIPOutputStream(new FileOutputStream(this.fileName + ".gz"));
byte[] buffer = new byte[1024];
int length;
while ((length = initialTxtFileInStream.read(buffer)) > 0) {
gZipOutStream.write(buffer, 0, length);
}
} catch (Exception e) {
LOGGER.error("Error writing file: " + Logger.getStackTrace(e));
}
try {
gZipOutStream.close();
initialTxtFileOutStream.close();
initialTxtFileInStream.close();
} catch (IOException e) {
LOGGER.warn("Error closing i/o streams involved in writing file: " + Logger.getStackTrace(e));
}
}