I have the contents I want to write to a file saved in Strings in my Java program. I need o write them to a .txt
file and then compress them into a .gz
archive. I'm able to do all of this, but when I extract the file from the .gz
archive, the extracted file no longer bear's the .txt
file extension.
This is my code below:
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));
}
}