-1
我有一段代碼,它使用deflate
算法壓縮的文件:Java 7的通貨緊縮時期文件
public static File compressOld(File rawFile) throws IOException
{
File compressed = new File(rawFile.getCanonicalPath().split("\\.")[0]
+ "_compressed." + rawFile.getName().split("\\.")[1]);
InputStream inputStream = new FileInputStream(rawFile);
OutputStream compressedWriter = new DeflaterOutputStream(new FileOutputStream(compressed));
byte[] buffer = new byte[1000];
int length;
while ((length = inputStream.read(buffer)) > 0)
{
compressedWriter.write(buffer, 0, length);
}
inputStream.close();
compressedWriter.close();
return compressed;
}
不過,我不開心與OutputStream
複製循環,因爲它的「過時」的方式寫入流。相反,我想用一個Java 7
API的方法,如Files.copy
:
public static File compressNew(File rawFile) throws IOException
{
File compressed = new File(rawFile.getCanonicalPath().split("\\.")[0]
+ "_compressed." + rawFile.getName().split("\\.")[1]);
OutputStream compressedWriter = new DeflaterOutputStream(new FileOutputStream(compressed));
Files.copy(compressed.toPath(), compressedWriter);
compressedWriter.close();
return compressed;
}
後一種方法但不能正常工作,壓縮文件被搞砸了,只有幾個字節複製。怎麼來的?
關於你的第一段代碼,沒有什麼'過時的'。它仍然有效。這裏沒有什麼不快樂的。不清楚你在問什麼,爲什麼。 – EJP