List of usage examples for java.util.zip ZipOutputStream write
public synchronized void write(byte[] b, int off, int len) throws IOException
From source file:org.dspace.app.itemexport.ItemExportServiceImpl.java
/** * // w w w . j a va2s . c o m * @param cpFile file * @param strSource source location * @param strTarget target location * @param cpZipOutputStream current zip outputstream * @throws Exception if error */ protected void zipFiles(File cpFile, String strSource, String strTarget, ZipOutputStream cpZipOutputStream) throws Exception { int byteCount; final int DATA_BLOCK_SIZE = 2048; FileInputStream cpFileInputStream = null; if (cpFile.isDirectory()) { File[] fList = cpFile.listFiles(); for (File aFList : fList) { zipFiles(aFList, strSource, strTarget, cpZipOutputStream); } } else { try { if (cpFile.getAbsolutePath().equalsIgnoreCase(strTarget)) { return; } String strAbsPath = cpFile.getPath(); String strZipEntryName = strAbsPath.substring(strSource.length() + 1, strAbsPath.length()); // byte[] b = new byte[ (int)(cpFile.length()) ]; cpFileInputStream = new FileInputStream(cpFile); ZipEntry cpZipEntry = new ZipEntry(strZipEntryName); cpZipOutputStream.putNextEntry(cpZipEntry); byte[] b = new byte[DATA_BLOCK_SIZE]; while ((byteCount = cpFileInputStream.read(b, 0, DATA_BLOCK_SIZE)) != -1) { cpZipOutputStream.write(b, 0, byteCount); } // cpZipOutputStream.write(b, 0, (int)cpFile.length()); } finally { if (cpFileInputStream != null) { cpFileInputStream.close(); } cpZipOutputStream.closeEntry(); } } }
From source file:com.esd.ps.WorkerController.java
/** * (wav?)//from www.j a v a2 s .c om * @param response * @param downTaskCount * @param session * @param request * @param packType * @return */ @RequestMapping(value = "/downTask", method = RequestMethod.GET) @ResponseBody public Map<String, Object> downTask(final HttpServletResponse response, int downTaskCount, HttpSession session, HttpServletRequest request, int packType) { Map<String, Object> map = new HashMap<String, Object>(); //session?user_id int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString()); //int workerId = workerService.getWorkerIdByUserId(Integer.parseInt(session.getAttribute(Constants.USER_ID).toString())); //workeruser_idworker worker w = workerService.getWorkerByUserId(userId); if (w == null) { map.put("replay", 1); return map; } //worker_id int workerId = w.getWorkerId(); //workerdowningworker? //downing = 1 if (w.getDowning() == 1) { map.put("replay", 1); return map; } else { //worker_recordworker_idworker?? int doingtaskcount = workerRecordService.getDoingTaskCountByWorkerId(workerId); if (doingtaskcount > 0) { map.put("replay", 1); return map; } } //sessiondowning?1 session.setAttribute("downing", 1); logger.debug("downTaskCount:{}", downTaskCount); //taskpack_type?? int countTaskDoing = taskService.getCountTaskDoing(packType); // ???? if (countTaskDoing < downTaskCount) { // String nowCountTaskDoing=countTaskDoing + ""; map.put(Constants.MESSAGE, MSG_TASK_NOT_ENOUGH); session.setAttribute("downing", 0); return map; } //String realName = workerService.getWorkerRealNameByWorkerId(workerId); //?worker?? String realName = w.getWorkerRealName(); // int packId = packService.getPackIdOrderByPackLvl(); // ? worker worker = new worker(); worker.setWorkerId(workerId); worker.setDowning(1); //workerdowning workerService.updateByPrimaryKeySelective(worker); //? String url = WorkerController.url(request); logger.debug("url:{}", url); // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); //??? String downPackName = sdf.format(new Date()) + Constants.UNDERLINE + downTaskCount + Constants.UNDERLINE + userId + Constants.POINT + Constants.ZIP; String wrongPath = Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + downPackName; //?list String downPackName,String wrongPath,String realName,String userName List<taskWithBLOBs> list = taskService.updateWorkerIdDowningTask(downTaskCount, 0, userId, workerId, packType, downPackName, wrongPath, realName, session.getAttribute(Constants.USER_NAME).toString()); if (list == null) { session.setAttribute("downing", 0); return null; } File f = new File(url); if (f.exists() == false) { f.mkdir(); } //? File zipFile = new File(url + Constants.SLASH + downPackName); if (zipFile.exists()) { zipFile.delete(); } // ??? // String serverAndProjectPath = request.getLocalAddr() + // Constants.COLON + request.getLocalPort() + request.getContextPath(); // ? // String wrongPath = Constants.HTTP + serverAndProjectPath + // Constants.SLASH + Constants.WORKERTEMP + Constants.SLASH + // downPackName; //?? logger.debug("wrongPath:{}", wrongPath); try { zipFile.createNewFile(); FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos)); byte[] bufs = new byte[1024 * 10]; for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) { taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next(); //?? String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName(); // ZIP, ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); //task?? byte[] data = taskWithBLOBs.getTaskWav(); //?? InputStream is = new ByteArrayInputStream(data); // ? BufferedInputStream bis = new BufferedInputStream(is, 1024); int read; while ((read = bis.read(bufs)) > 0) {// , 0, 2048 zos.write(bufs, 0, read);// } // zos.closeEntry(); bis.close(); is.close(); // task // worker_record // workerRecord workerRecord = new workerRecord(); // workerRecord.setCreateTime(new Date()); // workerRecord.setTaskOverTime(new Date()); // workerRecord.setDownPackName(downPackName); // workerRecord.setDownUrl(wrongPath); // workerRecord.setPackId(taskWithBLOBs.getPackId()); // workerRecord.setPackName(packService.getPackNameByPackId(taskWithBLOBs.getPackId())); // workerRecord.setTaskDownTime(new Date()); // workerRecord.setTaskId(taskWithBLOBs.getTaskId()); // int packLockTime = packService.getPackLockTime(taskWithBLOBs.getPackId()); // if (packLockTime > 0) { // workerRecord.setTaskLockTime(packLockTime); // } // workerRecord.setTaskName(taskWithBLOBs.getTaskName()); // //?? // workerRecord.setRealName(realName); // workerRecord.setTaskStatu(0); // workerRecord.setWorkerId(workerId); // workerRecord.setUserName(session.getAttribute(Constants.USER_NAME).toString()); // StackTraceElement[] items1 = Thread.currentThread().getStackTrace(); // workerRecord.setCreateMethod(items1[1].toString()); // workerRecordService.insertSelective(workerRecord); } session.setAttribute(Constants.WORKERMARK, 1); zos.close();// ,??0kb fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } /** * ,packStatus */ // if (taskService.getUndoTaskCountByPackId(packId) == 0) { // packWithBLOBs pack = new packWithBLOBs(); // pack.setPackId(packId); // pack.setPackStatus(2); // packService.updateByPrimaryKeySelective(pack); // } logger.debug("wrongPath:{}", wrongPath); map.put(Constants.WRONGPATH, wrongPath); map.put("replay", 0); session.setAttribute("downing", 0); // ? worker.setDowning(0); workerService.updateByPrimaryKeySelective(worker); return map; }
From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java
/** * @param expFile//from ww w . j a v a 2s.c o m * @param data * @param appRes * @throws IOException * * writes the contents of a report resource to a zip file. * Currently creates 3 entries: 1) AppResource, 2) AppResource data, * and if present, 3)SpReport, SpQuery, SpQueryFields. * */ //XXX implement support for subreports protected void writeSpReportResToZipFile(final File expFile, final String data, final AppResourceIFace appRes) throws IOException { StringBuilder sb = new StringBuilder(); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(expFile)); //the appResource name and metadata sb.append("<reportresource name=\"" + appRes.getName() + "\">\r\n"); sb.append("<metadata > <![CDATA["); sb.append(appRes.getMetaData()); sb.append("]]>"); sb.append("</metadata>\r\n"); sb.append("<mimetype > <![CDATA["); sb.append(appRes.getMimeType()); sb.append("]]>"); sb.append("</mimetype>\r\n"); sb.append("\r\n</reportresource>\r\n"); zout.putNextEntry(new ZipEntry("app.xml")); byte[] bytes = sb.toString().getBytes(); zout.write(bytes, 0, bytes.length); zout.closeEntry(); //the data zout.putNextEntry(new ZipEntry("data.xml")); bytes = data.getBytes(); zout.write(bytes, 0, bytes.length); zout.closeEntry(); //the spReport sb.setLength(0); DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { SpReport spRep = (SpReport) session .getData("from SpReport where appResourceId = " + ((SpAppResource) appRes).getId()); if (spRep != null) { spRep.forceLoad(); spRep.toXML(sb); bytes = sb.toString().getBytes(); zout.putNextEntry(new ZipEntry("SpReport.xml")); zout.write(bytes, 0, bytes.length); zout.closeEntry(); } } finally { session.close(); } zout.close(); }
From source file:edu.umd.cs.eclipse.courseProjectManager.TurninProjectAction.java
public void run(IAction action) { // TODO Refactor: Should the places where we raise a dialog and return // could throw an exception instead? String timeOfSubmission = "t" + System.currentTimeMillis(); // Make sure we can get the workbench... IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench == null) { Dialogs.errorDialog(null, "Warning: project submission failed", "Could not submit project", "Internal error: Can't get workbench", IStatus.ERROR); return;/*w w w. j a va 2s . c o m*/ } // ...and the workbenchWindow IWorkbenchWindow wwin = workbench.getActiveWorkbenchWindow(); if (wwin == null) { Dialogs.errorDialog(null, "Error submitting project", "Could not submit project", "Internal error: Can't get workbench window", IStatus.ERROR); return; } // Shell to use as parent of dialogs. Shell parent = wwin.getShell(); // Sanity check. if (!(selection instanceof IStructuredSelection)) { Dialogs.errorDialog(parent, "Warning: Selection is Invalid", "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.", "Object selected is not a Project", IStatus.WARNING); return; } IStructuredSelection structured = (IStructuredSelection) selection; Object obj = structured.getFirstElement(); Debug.print("Selection object is a " + obj.getClass().getName() + " @" + System.identityHashCode(obj)); IProject project; if (obj instanceof IProject) { project = (IProject) obj; } else if (obj instanceof IProjectNature) { project = ((IProjectNature) obj).getProject(); } else { Dialogs.errorDialog(null, "Warning: Selection is Invalid", "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.", "Object selected is not a Project", IStatus.WARNING); return; } Debug.print("Got the IProject for the turnin action @" + System.identityHashCode(project)); // ================================= save dirty editors // ======================================== // save dirty editors try { if (!saveDirtyEditors(project, workbench)) { Dialogs.errorDialog(parent, "Submit not performed", "Projects cannot be submitted unless all open files are saved", "Unsaved files prevent submission", IStatus.WARNING); return; } } catch (CoreException e) { Dialogs.errorDialog(parent, "Submit not performed", "Could not turn on cvs management for all project files", e); return; } // ========================= Add all non-ignored files in the project // ========================= IResource[] files; try { Set<IResource> resourceSet = getProjectResources(project); ArrayList<IFile> addedFiles = new ArrayList<IFile>(); for (Iterator<IResource> iter = resourceSet.iterator(); iter.hasNext();) { IResource resource = iter.next(); if (resource instanceof IFile) { IFile file = (IFile) resource; if (!AutoCVSPlugin.isCVSIgnored(file) && !AutoCVSPlugin.isCVSManaged(file)) { addedFiles.add(file); } } } files = (IResource[]) addedFiles.toArray(new IResource[addedFiles.size()]); } catch (CoreException e) { Dialogs.errorDialog(parent, "Submit not performed", "Could not perform submit; unable to find non-ignored resources", e); return; // TODO what to do here? } // ================================= perform CVS commit // ======================================== // TODO Somehow move this into the previous try block // This forces add/commit operations when AutoSync was shut off // Would it just be easier to enable autoSync and then trigger // a resource changed delta, since this method appears to enable // autoSync anyway? // String cvsStatus = "Not performed"; try { cvsStatus = forceCommit(project, files); } catch (Exception e) { Dialogs.errorDialog(parent, "CVS commit not performed as part of submission due to unexpected exception", e.getClass().getName() + " " + e.getMessage(), e); } // ================================= perform CVS tag // ======================================== try { CVSOperations.tagProject(project, timeOfSubmission, CVSOperations.SYNC); } catch (Exception e) { AutoCVSPlugin.getPlugin().getEventLog() .logError("Error tagging submission; submission via the web unlikely to work", e); } // ================================= find properties // ======================================== // find the .submitProject file IResource submitProjectFile = project.findMember(AutoCVSPlugin.SUBMITPROJECT); if (submitProjectFile == null) { Dialogs.errorDialog(parent, "Warning: Project submission not enabled", "Submission is not enabled", "There is no " + AutoCVSPlugin.SUBMITPROJECT + " file for the project", IStatus.ERROR); return; } // Get the properties from the .submit file, and the .submitUser file, // if it exists // or can be fetched from the server Properties allSubmissionProps = null; try { allSubmissionProps = getAllProperties(timeOfSubmission, parent, project, submitProjectFile); } catch (IOException e) { String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and " + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus; AutoCVSPlugin.getPlugin().getEventLog().logError(message, e); Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR); Debug.print("IOException: " + e); return; } catch (CoreException e) { String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and " + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus; AutoCVSPlugin.getPlugin().getEventLog().logError(message, e); Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR); Debug.print("CoreException: " + e); return; } // // THE ACTUAL SUBMIT HAPPENS HERE // try { // ============================== find files to submit // ==================================== Collection<IFile> cvsFiles = findFilesForSubmission(project); // ========================== assemble zip file in byte array // ============================== ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096); ZipOutputStream zipfile = new ZipOutputStream(bytes); zipfile.setComment("zipfile for submission created by CourseProjectManager version " + AutoCVSPlugin.getPlugin().getVersion()); try { byte[] buf = new byte[4096]; for (IFile file : cvsFiles) { if (!file.exists()) { Debug.print("Resource " + file.getName() + " being ignored because it doesn't exist"); continue; } ZipEntry entry = new ZipEntry(file.getProjectRelativePath().toString()); entry.setTime(file.getModificationStamp()); zipfile.putNextEntry(entry); // Copy file data to zip file InputStream in = file.getContents(); try { while (true) { int n = in.read(buf); if (n < 0) break; zipfile.write(buf, 0, n); } } finally { in.close(); } zipfile.closeEntry(); } } catch (IOException e1) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Unable to zip files for submission\n" + cvsStatus, e1); return; } finally { if (zipfile != null) zipfile.close(); } // ============================== Post to submit server // ==================================== String version = System.getProperties().getProperty("java.runtime.version"); boolean useEasyHttps = version.startsWith("1.3") || version.startsWith("1.2") || version.startsWith("1.4.0") || version.startsWith("1.4.1") || version.startsWith("1.4.2_0") && version.charAt(7) < '5'; if (useEasyHttps) { String submitURL = allSubmissionProps.getProperty("submitURL"); if (submitURL.startsWith("https")) submitURL = "easy" + submitURL; allSubmissionProps.setProperty("submitURL", submitURL); } // prepare multipart post method MultipartPostMethod filePost = new MultipartPostMethod(allSubmissionProps.getProperty("submitURL")); // add properties addAllPropertiesButSubmitURL(allSubmissionProps, filePost); // add filepart byte[] allInput = bytes.toByteArray(); filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput))); // prepare httpclient HttpClient client = new HttpClient(); client.setConnectionTimeout(5000); int status = client.executeMethod(filePost); // Piggy-back uploading the launch events onto submitting. EclipseLaunchEventLog.postEventLogToServer(project); if (status == HttpStatus.SC_OK) { Dialogs.okDialog(parent, "Project submission successful", "Project " + allSubmissionProps.getProperty("projectNumber") + " was submitted successfully\n" + filePost.getResponseBodyAsString()); } else { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submission failed", filePost.getStatusText() + "\n " + cvsStatus, IStatus.CANCEL); AutoCVSPlugin.getPlugin().getEventLog().logMessage(filePost.getResponseBodyAsString()); } } catch (CoreException e) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions via https failed\n" + cvsStatus, e); } catch (HttpConnection.ConnectionTimeoutException e) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions failed", "Connection timeout while trying to connect to submit server\n " + cvsStatus, IStatus.ERROR); } catch (IOException e) { Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions failed\n " + cvsStatus, e); } }
From source file:org.sakaiproject.metaobj.shared.mgt.impl.StructuredArtifactDefinitionManagerImpl.java
protected void storeFileInZip(ZipOutputStream zos, InputStream in, String entryName) throws IOException { byte data[] = new byte[1024 * 10]; if (File.separatorChar == '\\') { entryName = entryName.replace('\\', '/'); }/*from w w w . j av a 2 s. c om*/ ZipEntry newfileEntry = new ZipEntry(entryName); zos.putNextEntry(newfileEntry); BufferedInputStream origin = new BufferedInputStream(in, data.length); int count; while ((count = origin.read(data, 0, data.length)) != -1) { zos.write(data, 0, count); } zos.closeEntry(); in.close(); }
From source file:com.hichinaschool.flashcards.async.Connection.java
private Payload doInBackgroundUpgradeDecks(Payload data) { // Enable http request canceller mCancelCallback = new CancelCallback(); String path = (String) data.data[0]; File ankiDir = new File(path); if (!ankiDir.isDirectory()) { data.success = false;// w ww . j av a 2s . co m data.data = new Object[] { "wrong anki directory" }; return data; } // step 1: gather all .anki files into a zip, without media. // we must store them as 1.anki, 2.anki and provide a map so we don't run into // encoding issues with the zip file. File[] fileList = ankiDir.listFiles(new OldAnkiDeckFilter()); List<String> corruptFiles = new ArrayList<String>(); JSONObject map = new JSONObject(); byte[] buf = new byte[1024]; String zipFilename = path + "/upload.zip"; String colFilename = path + AnkiDroidApp.COLLECTION_PATH; try { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilename)); int n = 1; for (File f : fileList) { String deckPath = f.getAbsolutePath(); // set journal mode to delete try { AnkiDb d = AnkiDatabaseManager.getDatabase(deckPath); } catch (SQLiteDatabaseCorruptException e) { // ignore invalid .anki files corruptFiles.add(f.getName()); continue; } finally { AnkiDatabaseManager.closeDatabase(deckPath); } // zip file String tmpName = n + ".anki"; FileInputStream in = new FileInputStream(deckPath); ZipEntry ze = new ZipEntry(tmpName); zos.putNextEntry(ze); int len; while ((len = in.read(buf)) >= 0) { zos.write(buf, 0, len); } zos.closeEntry(); map.put(tmpName, f.getName()); n++; } // if all .anki files were found corrupted, abort if (fileList.length == corruptFiles.size()) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } ZipEntry ze = new ZipEntry("map.json"); zos.putNextEntry(ze); InputStream in = new ByteArrayInputStream(Utils.jsonToString(map).getBytes("UTF-8")); int len; while ((len = in.read(buf)) >= 0) { zos.write(buf, 0, len); } zos.closeEntry(); zos.close(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new RuntimeException(e); } File zipFile = new File(zipFilename); // step 1.1: if it's over 50MB compressed, it must be upgraded by the user if (zipFile.length() > 50 * 1024 * 1024) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_exceeds) }; return data; } // step 2: upload zip file to upgrade service and get token BasicHttpSyncer h = new BasicHttpSyncer(null, null); // note: server doesn't expect it to be gzip compressed, because the zip file is compressed // enable cancelling publishProgress(R.string.upgrade_decks_upload, null, true); try { HttpResponse resp = h.req("upgrade/upload", new FileInputStream(zipFile), 0, false, null, mCancelCallback); if (resp == null && !isCancelled()) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } String result; String key = null; if (!isCancelled()) { result = h.stream2String(resp.getEntity().getContent()); if (result != null && result.startsWith("ok:")) { key = result.split(":")[1]; } else { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } } while (!isCancelled()) { result = h.stream2String(h.req("upgrade/status?key=" + key).getEntity().getContent()); if (result.equals("error")) { data.success = false; data.data = new Object[] { "error" }; return data; } else if (result.startsWith("waiting:")) { publishProgress(R.string.upgrade_decks_upload, result.split(":")[1]); } else if (result.equals("upgrading")) { publishProgress(new Object[] { R.string.upgrade_decks_upgrade_started }); } else if (result.equals("ready")) { break; } else { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } Thread.sleep(1000); } // step 4: fetch upgraded file. this will return the .anki2 file directly, with // gzip compression if the client says it can handle it if (!isCancelled()) { publishProgress(new Object[] { R.string.upgrade_decks_downloading }); resp = h.req("upgrade/download?key=" + key, null, 6, true, null, mCancelCallback); // uploads/downloads have finished so disable cancelling } publishProgress(R.string.upgrade_decks_downloading, null, false); if (isCancelled()) { return null; } if (resp == null) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } // step 5: check the received file is valid InputStream cont = resp.getEntity().getContent(); if (!h.writeToFile(cont, colFilename)) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_sdcard, new File(colFilename).length() / 1048576 + 1) }; (new File(colFilename)).delete(); return data; } // check the received file is ok publishProgress(new Object[] { R.string.sync_check_download_file }); publishProgress(R.string.sync_check_download_file); try { AnkiDb d = AnkiDatabaseManager.getDatabase(colFilename); if (!d.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) { data.success = false; data.data = new Object[] { sContext.getResources() }; return data; } } finally { AnkiDatabaseManager.closeDatabase(colFilename); } Collection col = AnkiDroidApp.openCollection(colFilename); ArrayList<String> decks = col.getDecks().allNames(false); ArrayList<String> failed = new ArrayList<String>(); ArrayList<File> mediaDirs = new ArrayList<File>(); for (File f : fileList) { String name = f.getName().replaceFirst("\\.anki$", ""); if (!decks.contains(name)) { failed.add(name); } else { mediaDirs.add(new File(f.getAbsolutePath().replaceFirst("\\.anki$", ".media"))); } } File newMediaDir = new File(col.getMedia().getDir()); // step 6. move media files to new media directory publishProgress(new Object[] { R.string.upgrade_decks_media }); ArrayList<String> failedMedia = new ArrayList<String>(); File curMediaDir = null; for (File mediaDir : mediaDirs) { curMediaDir = mediaDir; // Check if media directory exists and is local if (!curMediaDir.exists() || !curMediaDir.isDirectory()) { // If not try finding it in dropbox 1.2.x curMediaDir = new File(AnkiDroidApp.getDropboxDir(), mediaDir.getName()); if (!curMediaDir.exists() || !curMediaDir.isDirectory()) { // No media for this deck continue; } } // Found media dir, copy files for (File m : curMediaDir.listFiles()) { try { Utils.copyFile(m, new File(newMediaDir, m.getName())); } catch (IOException e) { failedMedia.add(curMediaDir.getName().replaceFirst("\\.media$", ".anki")); break; } } } data.data = new Object[] { failed, failedMedia, newMediaDir.getAbsolutePath() }; data.success = true; return data; } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (IllegalStateException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { (new File(zipFilename)).delete(); } }
From source file:marytts.tools.voiceimport.VoicePackager.java
/** * Create zip file containing all of the voice files (including the config file, which should be in <b>files</b>). * //www . j a v a2 s . co m * @param files * <property, File> Map, e.g. "WaveTimelineMaker.waveTimeline" → * File("VOICE_DIR/mary/timeline_waves.mry") * @return the zip File object * @throws Exception */ protected File createZipFile(HashMap<String, File> files) throws Exception { // TODO this should probably be optimized by using buffered Readers and Writer: byte[] buffer = new byte[4096]; // initialize zip file: String zipFileName = String.format("mary-%s-%s.zip", getVoiceName(), getMaryVersion()); logger.info("Creating voice package " + zipFileName); File zipFile = new File(getMaryBase() + "download" + File.separator + zipFileName); FileOutputStream outputStream = new FileOutputStream(zipFile); ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zipFile)); // TODO this doesn't explicitly create each ancestor of the voicePath as a separate directory entry in the zip file, but // that doesn't seem necessary: String voicePath = "lib" + File.separator + "voices" + File.separator + getVoiceName() + File.separator; // iterate over files: for (String key : files.keySet()) { File file = files.get(key); // open data file for reading: FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { if (key.equals(EXAMPLETEXTFILE) && getProp(EXAMPLETEXTFILE).length() == 0 && !getVoiceDomain().equalsIgnoreCase("limited")) { logger.debug("Example text file " + getProp(EXAMPLETEXTFILE) + " not found, ignoring."); continue; } else { logger.error("File " + file + " not found!"); throw e; } } // make new entry in zip file, with the appropriate target path: logger.debug("Deflating file " + file); if (key.equals("CONFIG")) { zipStream.putNextEntry(new ZipEntry("conf" + File.separator + file.getName())); } else { zipStream.putNextEntry(new ZipEntry(voicePath + file.getName())); } int len; // stream file contents into zip file: while ((len = inputStream.read(buffer)) > 0) { zipStream.write(buffer, 0, len); } // complete entry and close data file: zipStream.closeEntry(); inputStream.close(); } // close zip file: zipStream.close(); return zipFile; }
From source file:org.openmeetings.servlet.outputhandler.BackupExport.java
public void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(file); // we want the zipEntry's path to be a relative path that is relative // to the directory being zipped, so chop off the rest of the path String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1, file.getCanonicalPath().length()); log.debug("Writing '" + zipFilePath + "' to zip file"); ZipEntry zipEntry = new ZipEntry(zipFilePath); zos.putNextEntry(zipEntry);//from w w w. j a v a 2 s.c o m byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fis.close(); }
From source file:com.pari.pcb.zip.ZIPProcessor.java
private static void writeToZip(File f, String fileName, ZipOutputStream zout) throws IOException { FileInputStream fis = null;//from w w w . j a v a 2 s. co m try { if (f.isDirectory()) { File files[] = f.listFiles(); for (File f1 : files) { writeToZip(f1, fileName + "/" + f1.getName(), zout); } return; } ZipEntry ze = new ZipEntry(fileName); zout.putNextEntry(ze); byte b[] = new byte[1024]; fis = new FileInputStream(f); int n = 0; while ((n = fis.read(b)) >= 0) { zout.write(b, 0, n); } fis.close(); zout.closeEntry(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }