下面列出了java.util.zip.ZipOutputStream#flush ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void addFileToZip(ZipOutputStream zos, File base, File file)
throws IOException {
byte[] buffer = new byte[1024];
try (FileInputStream fis = new FileInputStream(file)) {
String name = base.toURI().relativize(file.toURI()).getPath();
LOG.info("Adding file {} to zip", name);
zos.putNextEntry(new ZipEntry(name));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.flush();
} finally {
zos.closeEntry();
}
}
@Test
public void testZip() throws Exception {
File testFile = File.createTempFile("adasda","Dsdasdea");
INDArray arr = Nd4j.create(new double[]{1,2,3,4,5,6,7,8,9,0});
final FileOutputStream fileOut = new FileOutputStream(testFile);
final ZipOutputStream zipOut = new ZipOutputStream(fileOut);
zipOut.putNextEntry(new ZipEntry("params"));
Nd4j.write(zipOut, arr);
zipOut.flush();
zipOut.close();
final FileInputStream fileIn = new FileInputStream(testFile);
final ZipInputStream zipIn = new ZipInputStream(fileIn);
ZipEntry entry = zipIn.getNextEntry();
INDArray read = Nd4j.read(zipIn);
zipIn.close();
assertEquals(arr, read);
}
public void exportToZip(OutputStream os) throws WPBIOException
{
ZipOutputStream zos = new ZipOutputStream(os);
exportUris(zos, PATH_URIS);
exportSitePages(zos, PATH_SITE_PAGES);
exportPageModules(zos, PATH_SITE_PAGES_MODULES);
exportMessages(zos, PATH_MESSAGES);
exportFiles(zos, PATH_FILES);
exportArticles(zos, PATH_ARTICLES);
exportGlobals(zos, PATH_GLOBALS);
exportLocales(zos, PATH_LOCALES);
try
{
zos.flush();
zos.close();
} catch (IOException e)
{
log.log(Level.SEVERE, e.getMessage(), e);
throw new WPBIOException("Cannot export project, error flushing/closing stream", e);
}
}
public void exportToZip(OutputStream os) throws WPBIOException
{
ZipOutputStream zos = new ZipOutputStream(os);
exportUris(zos, PATH_URIS);
exportSitePages(zos, PATH_SITE_PAGES);
exportPageModules(zos, PATH_SITE_PAGES_MODULES);
exportMessages(zos, PATH_MESSAGES);
exportFiles(zos, PATH_FILES);
exportArticles(zos, PATH_ARTICLES);
exportGlobals(zos, PATH_GLOBALS);
exportLocales(zos, PATH_LOCALES);
try
{
zos.flush();
zos.close();
} catch (IOException e)
{
log.log(Level.SEVERE, e.getMessage(), e);
throw new WPBIOException("Cannot export project, error flushing/closing stream", e);
}
}
/**
* 压缩文件
*
* @param resFile 需要压缩的文件(夹)
* @param zipout 压缩的目的文件
* @param rootpath 压缩的文件路径
* @throws FileNotFoundException 找不到文件时抛出
* @throws IOException 当压缩过程出错时抛出
*/
private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath)
throws FileNotFoundException, IOException {
rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator)
+ resFile.getName();
rootpath = new String(rootpath.getBytes("8859_1"), "GB2312");
if (resFile.isDirectory()) {
File[] fileList = resFile.listFiles();
for (File file : fileList) {
zipFile(file, zipout, rootpath);
}
} else {
byte buffer[] = new byte[BUFF_SIZE];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile),
BUFF_SIZE);
zipout.putNextEntry(new ZipEntry(rootpath));
int realLength;
while ((realLength = in.read(buffer)) != -1) {
zipout.write(buffer, 0, realLength);
}
in.close();
zipout.flush();
zipout.closeEntry();
}
}
private static File createZip(Map<String, String> files) throws Exception {
File f = Os.newTempFile("osgi", "zip");
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(f));
for (Map.Entry<String, String> entry : files.entrySet()) {
ZipEntry ze = new ZipEntry(entry.getKey());
zip.putNextEntry(ze);
zip.write(entry.getValue().getBytes());
}
zip.closeEntry();
zip.flush();
zip.close();
return f;
}
public static void packZip(List<File> sources, File output) throws IOException {
EditorLogger.debug("Packaging to " + output.getName());
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(output));
zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
for (File source : sources) {
if (source.isDirectory()) {
zipDir(zipOut, "", source);
} else {
zipFile(zipOut, "", source);
}
}
zipOut.flush();
zipOut.close();
EditorLogger.debug("Done");
}
private static void streamDirectory(File directory, OutputStream os) {
try {
// Start the ZipStream reader. Whatever is read is streamed to response
PipedInputStream pis = new PipedInputStream(2048);
ZipStreamer pipestreamer = new ZipStreamer(pis, os);
pipestreamer.start();
// Start Zipping folder and piping to the ZipStream reader
PipedOutputStream pos = new PipedOutputStream(pis);
ZipOutputStream zos = new ZipOutputStream(pos);
StorageHandler.zipAndStream(directory, zos, directory.getName() + "/");
zos.flush();
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Zips the directory and all of it's sub directories
*
* @param zipFile
* the file to write the files into, never <code>null</code>
* @param directoryToZip
* the directory to zip, never <code>null</code>
* @throws Exception
* if the zip file could not be created
* @throws IllegalArgumentException
* if the directoryToZip is not a directory
*/
public static void zipDir( File zipFile, File directoryToZip )
throws Exception {
if ( !directoryToZip.isDirectory() ) {
throw new IllegalArgumentException( "Directory to zip is not a directory" );
}
try {
ZipOutputStream out = new ZipOutputStream( new FileOutputStream( zipFile ) );
File parentDir = new File( directoryToZip.toURI().resolve( ".." ) );
for ( File file : directoryToZip.listFiles() ) {
zip( parentDir, file, out );
}
out.flush();
out.close();
} catch ( IOException e ) {
throw new Exception( e.getMessage() );
}
}
/**
*
*/
public void zipEntries(OutputStream os) throws IOException
{
ZipOutputStream zipos = new ZipOutputStream(os);
zipos.setMethod(ZipOutputStream.DEFLATED);
for (String name : exportZipEntries.keySet())
{
ExportZipEntry exportZipEntry = exportZipEntries.get(name);
ZipEntry zipEntry = new ZipEntry(exportZipEntry.getName());
zipos.putNextEntry(zipEntry);
exportZipEntry.writeData(zipos);
}
zipos.flush();
zipos.finish();
}
public static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException {
String rootpath2 = new String(new StringBuilder(String.valueOf(rootpath)).append(rootpath.trim().length() == 0 ? "" : File.separator).append(resFile.getName()).toString().getBytes("8859_1"), "GB2312");
if (resFile.isDirectory()) {
for (File file : resFile.listFiles()) {
zipFile(file, zipout, rootpath2);
}
return;
}
byte[] buffer = new byte[1048576];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), 1048576);
zipout.putNextEntry(new ZipEntry(rootpath2));
while (true) {
int realLength = in.read(buffer);
if (realLength == -1) {
in.close();
zipout.flush();
zipout.closeEntry();
return;
}
zipout.write(buffer, 0, realLength);
}
}
@Override
public final void doArchiver(File[] files, String destpath)
throws IOException {
/*
* 定义一个ZipOutputStream 对象
*/
FileOutputStream fos = new FileOutputStream(destpath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);
dfs(files, zos, "");
zos.flush();
zos.close();
}
@Override
public void close() throws IOException {
ZipOutputStream zos = (ZipOutputStream) delegate;
zos.flush();
zos.closeEntry();
zos.finish();
zos.close();
}
/**
* Flattens(serializes, dehydrates, etc.) this instance to a binary representation.
*
* @return a binary representation
* @throws IOException
*/
public byte[] toBytes() throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ZipOutputStream stream = new ZipOutputStream(bout);
ZipEntry ze = new ZipEntry("async_message");
stream.putNextEntry(ze);
stream.write(toXml().getBytes());
stream.flush();
stream.close();
return bout.toByteArray();
}
public void compress(OutputStream out) throws IOException {
ZipOutputStream zOut = new ZipOutputStream(out);
// zOut.setLevel(Deflater.BEST_SPEED);
zOut.putNextEntry(new ZipEntry("A"));
DataOutputStream dOut = new DataOutputStream(zOut);
dOut.writeInt(mUnits.length);
for (int ii = 0; ii < mUnits.length; ii++) {
dOut.writeLong(mUnits[ii]);
}
dOut.flush();
zOut.closeEntry();
zOut.flush();
}
/**
* 转换器的处理顺序如下:<br/>
* 1. 解析 XLIFF 文件,获取所有文本段并存放入集合中。<br/>
* 2. 将骨架文件解压到临时目录。<br/>
* 3. 将临时目录中除 Stories 文件夹之外的其他文件及 Stories 文件夹中以 .xml 结尾的文件放入目标文件。<br/>
* 4. 解析 Stories 文件夹中以 .skl 结尾的文件,并替换文件中的骨架信息,替换完成之后将此文件去除 .skl 后缀放入目标文件。<br/>
* 5. 删除临时解压目录。<br/>
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
monitor.beginTask("", 5);
// 转换过程分为 11 部分,loadSegment 占 1,releaseSklZip 占 1,createZip 占 1, handleStoryFile 占 7,deleteFileOrFolder 占 1
IProgressMonitor firstMonitor = Progress.getSubMonitor(monitor, 1);
firstMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task2"), 1);
firstMonitor.subTask("");
Map<String, String> result = new HashMap<String, String>();
strXLIFFPath = args.get(Converter.ATTR_XLIFF_FILE);
String strTgtPath = args.get(Converter.ATTR_TARGET_FILE);
strSklPath = args.get(Converter.ATTR_SKELETON_FILE);
try {
zipOut = new ZipOutputStream(new FileOutputStream(strTgtPath));
if (firstMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("idml.cancel"));
}
loadSegment();
firstMonitor.worked(1);
firstMonitor.done();
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("idml.cancel"));
}
IProgressMonitor secondMonitor = Progress.getSubMonitor(monitor, 1);
secondMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task3"), 1);
secondMonitor.subTask("");
// 将骨架文件解压到临时目录。
releaseSklZip(strSklPath);
secondMonitor.worked(1);
secondMonitor.done();
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("idml.cancel"));
}
IProgressMonitor thirdMonitor = Progress.getSubMonitor(monitor, 1);
thirdMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task4"), 1);
thirdMonitor.subTask("");
fileManager.createZip(strTmpFolderPath, zipOut, strTmpFolderPath + File.separator + "Stories");
thirdMonitor.worked(1);
thirdMonitor.done();
handleStoryFile(Progress.getSubMonitor(monitor, 7));
zipOut.flush();
zipOut.close();
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("idml.cancel"));
}
IProgressMonitor fourthMonitor = Progress.getSubMonitor(monitor, 1);
fourthMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task5"), 1);
fourthMonitor.subTask("");
// 删除解压目录
fileManager.deleteFileOrFolder(new File(strTmpFolderPath));
fourthMonitor.worked(1);
fourthMonitor.done();
result.put(Converter.ATTR_TARGET_FILE, strTgtPath);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(Messages.getString("idml.XLIFF2IDML.logger1"), e);
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("idml.XLIFF2IDML.msg1"),
e);
} finally {
monitor.done();
}
return result;
}
public static String[] stripSigning(String inputFile, String outputFile)
throws Exception {
ZipInputStream zis = new ZipInputStream(new FileInputStream(inputFile));
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
outputFile));
ZipEntry entry = null;
String resultString[] = null;
while ((entry = zis.getNextEntry()) != null) {
if (entry.getName().contains("META-INF"))
continue;
zos.putNextEntry(new ZipEntry(entry.getName()));
int size;
ByteBuffer bb = ByteBuffer.allocate(500000);
byte[] buffer = new byte[2048];
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
zos.write(buffer, 0, size);
if (entry.getName().endsWith("AndroidManifest.xml")) {
bb.put(buffer, 0, size);
}
}
zos.flush();
zos.closeEntry();
if (bb.position() > 0) {
buffer = new byte[bb.position()];
bb.rewind();
bb.get(buffer);
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
docFactory.setNamespaceAware(true); // never forget this!
docFactory.setIgnoringComments(true);
docFactory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = docFactory.newDocumentBuilder();
String packageName = "";
String mainActivity = "";
String docStr = AXMLToXML(buffer).replaceAll("\n", "");
Pattern pattern = Pattern
.compile("<activity.*?android:name=\"(.*?)\".*?</activity>");
Matcher m = pattern.matcher(docStr);
while (m.find()) {
String result = m.group();
if (result.contains("android.intent.action.MAIN")
&& result
.contains("android.intent.category.LAUNCHER")) {
mainActivity = (m.group(1));
}
}
pattern = Pattern.compile("<manifest.*?package=\"(.*?)\"");
m = pattern.matcher(docStr);
if (m.find()) {
packageName = m.group(1);
}
mainActivity = mainActivity.replaceAll(packageName, "");
resultString = new String[]{packageName,
packageName + mainActivity};
}
}
zis.close();
zos.close();
return resultString;
}
/**
* 压缩目录下的文件列表
* @param dirPath
* @param outFile
* @param filter
* @throws Exception
*/
public static final void zipFiles(String dirPath,String outFile,FileFilter filter) throws Exception
{
if(dirPath==null)
{
throw new IllegalArgumentException("dir ==null");
}
File dir=new File(dirPath);
if(dir.isFile())
{
throw new IllegalArgumentException("dir "+dir+" is not a dir");
}
if(!dir.exists())
{
throw new IllegalArgumentException("dir "+dir+" not found");
}
ZipOutputStream zos = new ZipOutputStream(new CheckedOutputStream(new FileOutputStream(outFile), new CRC32()));
try {
String rootDir=dir.getPath();
Stack<File> dirs = new Stack<File>();
dirs.push(dir);
while (!dirs.isEmpty())
{
File path = dirs.pop();
File[] fs = path.listFiles(filter);
for (File subFile : fs)
{
String subPath=subFile.getPath().replace(rootDir+File.separator,"");
byte[] data=new byte[] {};
if (subFile.isDirectory())
{//文件夹
dirs.push(subFile);
subPath+="/";
}else
{
if(subFile.getPath().equals(new File(outFile).getPath()))
{
continue;
}
data=Files.readAllBytes(Paths.get(subFile.getPath()));
}
ZipEntry entry = new ZipEntry(subPath);
zos.putNextEntry(entry);
zos.write(data);
}
}
zos.flush();
} finally {
zos.close();
}
}
/**
*
* Create zip file to interpreter.
* The contents are all the stuff under ZEPPELIN_HOME/interpreter/{interpreter_name}
* @return
* @throws IOException
*/
private File createInterpreterZip() throws IOException {
File interpreterArchive = File.createTempFile("zeppelin_interpreter_", ".zip", Files.createTempDir());
ZipOutputStream interpreterZipStream = new ZipOutputStream(new FileOutputStream(interpreterArchive));
interpreterZipStream.setLevel(0);
String zeppelinHomeEnv = System.getenv("ZEPPELIN_HOME");
if (org.apache.commons.lang3.StringUtils.isBlank(zeppelinHomeEnv)) {
throw new IOException("ZEPPELIN_HOME is not specified");
}
File zeppelinHome = new File(zeppelinHomeEnv);
File binDir = new File(zeppelinHome, "bin");
addFileToZipStream(interpreterZipStream, binDir, null);
File confDir = new File(zeppelinHome, "conf");
addFileToZipStream(interpreterZipStream, confDir, null);
File interpreterDir = new File(zeppelinHome, "interpreter/" + launchContext.getInterpreterSettingGroup());
addFileToZipStream(interpreterZipStream, interpreterDir, "interpreter");
File localRepoDir = new File(zConf.getInterpreterLocalRepoPath() + "/"
+ launchContext.getInterpreterSettingName());
if (localRepoDir.exists() && localRepoDir.isDirectory()) {
LOGGER.debug("Adding localRepoDir {} to interpreter zip: ", localRepoDir.getAbsolutePath());
addFileToZipStream(interpreterZipStream, localRepoDir, "local-repo");
}
// add zeppelin-interpreter-shaded jar
File[] interpreterShadedFiles = new File(zeppelinHome, "interpreter").listFiles(
file -> file.getName().startsWith("zeppelin-interpreter-shaded")
&& file.getName().endsWith(".jar"));
if (interpreterShadedFiles.length == 0) {
throw new IOException("No zeppelin-interpreter-shaded jar found under " +
zeppelinHome.getAbsolutePath() + "/interpreter");
}
if (interpreterShadedFiles.length > 1) {
throw new IOException("More than 1 zeppelin-interpreter-shaded jars found under "
+ zeppelinHome.getAbsolutePath() + "/interpreter");
}
addFileToZipStream(interpreterZipStream, interpreterShadedFiles[0], "interpreter");
interpreterZipStream.flush();
interpreterZipStream.close();
return interpreterArchive;
}
/**
* Writes the given repository as ZIP-File into the given output stream.
*
* @param outputStream the output stream that should receive the zipfile.
* @param repository the repository that should be written.
* @throws IOException if an IO error prevents the writing of the file.
* @throws ContentIOException if a repository related IO error occurs.
*/
public static void writeAsZip( final OutputStream outputStream,
final Repository repository ) throws IOException, ContentIOException {
final ZipOutputStream zipout = new ZipOutputStream( outputStream );
writeToZipStream( zipout, repository );
zipout.finish();
zipout.flush();
}