我在下载gzip文件并将其保存在 Java 5 的文件系统中时遇到问题。下载完成后,文件(具有正确的名称和扩展名)似乎具有不同的 MIME 类型......我无法从我的 Linux 服务器(使用gunzip)解压缩它,如果我尝试在我的 Windows 电脑上使用 WinZip 打开它,我会看到一个“递归”存档(如俄罗斯套娃)。如果我file *filename*.gz从服务器键入命令,它会将文件识别为ascii text. 相反,如果我尝试使用浏览器下载存档,一切顺利,我可以正确打开和解压缩文件(即使使用我的 Linux 服务器),现在它被识别为gzip compressed archive.
这是我用来下载文件并保存的代码。
主.java:
public class Main {
public static void main(String[] args) {
String filePath = "";
HttpOutgoingCall httpOngoingCall = null;
httpOngoingCall = new HttpOutgoingCall();
String endpointUrl = "https://myurl/myfile.gz";
try {
InputStream inputStream = httpOngoingCall.callHttps(endpointUrl);
//I also tried with ZipInputStream and GZIPInputStream
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
filePath = parseAndWriteResponse(br, "myfile.gz", "C:\\");
System.out.println(filePath);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static String parseAndWriteResponse(BufferedReader br, String fileName,
String destPath) {
String outputFileName = null;
outputFileName = destPath + File.separator + fileName;
String line;
File outputFile = new File(outputFileName);
FileWriter fileWriter = null;
BufferedWriter bw = null;
try {
if (!outputFile.exists()) {
outputFile.createNewFile();
}
} catch (IOException e1) {
}
try {
fileWriter = new FileWriter(outputFile);
bw = new BufferedWriter(fileWriter);
while ((line = br.readLine()) != null) {
bw.write(line);
bw.write("\n");
}
} catch (IOException e) {
} finally {
try {
bw.close();
fileWriter.close();
} catch (IOException e) {
}
}
return outputFileName;
}
相关分类