private void doSaveImage(final String diagramFileString, BpmnMemoryModel model) { boolean saveImage = PreferencesUtil.getBooleanPreference(Preferences.SAVE_IMAGE, ActivitiPlugin.getDefault()); if (saveImage) { List<String> languages = PreferencesUtil.getStringArray( Preferences.ACTIVITI_LANGUAGES, ActivitiPlugin.getDefault()); if (languages != null && languages.size() > 0) { for (String language : languages) { for (Process process : model.getBpmnModel().getProcesses()) { fillContainerWithLanguage(process, language); } ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator(); InputStream imageStream = processDiagramGenerator.generatePngDiagram(model.getBpmnModel()); if (imageStream != null) { String imageFileName = null; if (diagramFileString.endsWith(".bpmn20.xml")) { imageFileName = diagramFileString.substring(0, diagramFileString.length() - 11) + "_" + language + ".png"; } else { imageFileName = diagramFileString.substring(0, diagramFileString.lastIndexOf(".")) + "_" + language + ".png"; } File imageFile = new File(imageFileName); FileOutputStream outStream = null; ByteArrayOutputStream baos = null; try { outStream = new FileOutputStream(imageFile); baos = new ByteArrayOutputStream(); IOUtils.copy(imageStream, baos); baos.writeTo(outStream); } catch (Exception e) { e.printStackTrace(); } finally { if (outStream != null) { IOUtils.closeQuietly(outStream); } if (baos != null) { IOUtils.closeQuietly(baos); } } } } } else { marshallImage(model, diagramFileString); } } }
/** * Build a PDF report for the Sonar project on "sonar.base.url" instance of Sonar. The property * "sonar.base.url" is set in report.properties, this file will be provided by the artifact * consumer. * * <p>The key of the project is not place in properties, this is provided in execution time. * * @throws ReportException */ @Test( enabled = true, groups = {"report"}, dependsOnGroups = {"metrics"}) public void getReportTest() throws DocumentException, IOException, org.dom4j.DocumentException, ReportException { URL resource = this.getClass().getClassLoader().getResource("report.properties"); Properties config = new Properties(); config.load(resource.openStream()); config.setProperty("sonar.base.url", "http://localhost:9000"); URL resourceText = this.getClass().getClassLoader().getResource("report-texts-en.properties"); Properties configText = new Properties(); configText.load(resourceText.openStream()); PDFReporter reporter = new TeamWorkbookPDFReporter( this.getClass().getResource("/sonar.png"), "org.apache.struts:struts-parent", "http://localhost:9000", config, configText); ByteArrayOutputStream baos = reporter.getReport(); FileOutputStream fos = null; fos = new FileOutputStream("target/testReport.pdf"); baos.writeTo(fos); fos.flush(); fos.close(); }
public static File saveBitmap(Bitmap bmp, String id, Context context) { File file = getFile(id, context); if (!file.exists() && !file.isDirectory()) { try { FileOutputStream out = new FileOutputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int quality = 100; bmp.compress(Bitmap.CompressFormat.PNG, quality, baos); Log.d("图片压缩前大小:" + baos.toByteArray().length / 1024 + "kb"); if (baos.toByteArray().length / 1024 > 50) { quality = 80; baos.reset(); bmp.compress(Bitmap.CompressFormat.PNG, quality, baos); Log.d("质量压缩到原来的" + quality + "%时大小为:" + baos.toByteArray().length / 1024 + "kb"); } Log.d("图片压缩后大小:" + baos.toByteArray().length / 1024 + "kb"); baos.writeTo(out); baos.flush(); baos.close(); out.close(); // bmp.compress(Bitmap.CompressFormat.JPEG, 100, out); } catch (Exception e) { e.printStackTrace(); } } return file; }
protected synchronized void writeCache() { if (!mTargetFile.exists()) { try { mTargetFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } if (mByteOutput != null && mByteOutput.size() > 0 && mOutputStream != null) { try { mByteOutput.writeTo(mOutputStream); mLoadedByteLength += mByteOutput.size(); mByteOutput.reset(); } catch (IOException e) { e.printStackTrace(); } } if (mLoadedByteLength >= mTotalByteLength) { mTargetFile.renameTo(new File(getFilePath())); if (mException == null && mDownloadManager != null) { mDownloadManager.onFinishDownload(this); } return; } if (mDownloadManager != null) { mDownloadManager.onReceiveDownloadData(this); } }
/** Generate output JAR-file and packages */ public void outputToJar() throws IOException { // create the manifest final Manifest manifest = new Manifest(); final java.util.jar.Attributes atrs = manifest.getMainAttributes(); atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION, "1.2"); final Map map = manifest.getEntries(); // create manifest Enumeration classes = _bcelClasses.elements(); final String now = (new Date()).toString(); final java.util.jar.Attributes.Name dateAttr = new java.util.jar.Attributes.Name("Date"); while (classes.hasMoreElements()) { final JavaClass clazz = (JavaClass) classes.nextElement(); final String className = clazz.getClassName().replace('.', '/'); final java.util.jar.Attributes attr = new java.util.jar.Attributes(); attr.put(dateAttr, now); map.put(className + ".class", attr); } final File jarFile = new File(_destDir, _jarFileName); final JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest); classes = _bcelClasses.elements(); while (classes.hasMoreElements()) { final JavaClass clazz = (JavaClass) classes.nextElement(); final String className = clazz.getClassName().replace('.', '/'); jos.putNextEntry(new JarEntry(className + ".class")); final ByteArrayOutputStream out = new ByteArrayOutputStream(2048); clazz.dump(out); // dump() closes it's output stream out.writeTo(jos); } jos.close(); }
/** * Converts a given text file into a audio file of WAVE format. * * @param inputFile The input file path. Cannot be null or empty. * @throws Exception */ public void convertText2Audio(String inputFile) throws Exception { // Verify the file name if (StringUtils.isEmpty(inputFile)) { throw new IllegalArgumentException("Invalid file path"); } LOGGER.debug("Starting conversion of file : " + inputFile); // Timing the conversion process long startTime = System.nanoTime(); // TODO: This is very memory inefficient. String inputText = FileUtils.readFileToString(new File(inputFile)); // Text to Audio format conversion ByteArrayOutputStream audioOutputStream = new ByteArrayOutputStream(); MaryClient mary = MaryClient.getMaryClient(new Address(maryHostname, maryPort)); mary.process(inputText, inputType, outputType, locale, audioType, voiceName, audioOutputStream); // The byte array constitutes a full wave file, including the header. Write the byte array to // file. FileOutputStream fileOut = new FileOutputStream(getOutputFile(inputFile)); audioOutputStream.writeTo(fileOut); audioOutputStream.flush(); fileOut.close(); // Timing purpose long endTime = System.nanoTime(); long duration = (endTime - startTime); LOGGER.info( "Conversion time for file : " + inputFile + " took " + duration / 1000000000.0 + " secs"); }
private void writeBuf() throws IOException { if (buf.size() > 0) { if (zeroAdditions && (buf.size() >= this.zeroMinBlock) && (winRatio < zeroRatio)) { int s = buf.size(); buf.reset(); for (int i = 0; i < s; i++) { buf.write(0); } } if (buf.size() <= data_max) { output.writeByte(buf.size()); written += buf.size() + 1; } else if (buf.size() <= 32767) { output.writeByte(DATA_USHORT); output.writeShort(buf.size()); written += buf.size() + 3; } else { output.writeByte(DATA_INT); output.writeInt(buf.size()); written += buf.size() + 5; } buf.writeTo(output); buf.reset(); } }
@Override public OutputContext endContext() throws IOException { ByteArrayOutputStream out = (ByteArrayOutputStream) out(); parent.varint(out.size()); out.writeTo(parent.out()); return super.endContext(); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String sessionName = request.getParameter(PRM_SESSION_BUFFER); if (sessionName != null) { if (request.getSession().getAttribute(sessionName) != null) { MemoryFileBuffer mfb = (MemoryFileBuffer) request.getSession().getAttribute(sessionName); request.getSession().removeAttribute(sessionName); MemoryInputStream mis = new MemoryInputStream(mfb); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Read the entire contents of the file. while (mis.available() > 0) { baos.write(mis.read()); } response.setContentType(mfb.getMimeType()); response.setContentLength(baos.size()); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); mis.close(); baos.close(); } } } catch (Exception e2) { e2.printStackTrace(); System.out.println("Error in " + getClass().getName() + "\n" + e2); } }
/** * 从下载文件到本地 * * @param repository svn repos对象 * @param remotePath 下载目标路径,相对与svn根路径 * @param savePath 保存位置 * @param revision 版本 * @throws Exception */ private static void getFile( SVNRepository repository, String remotePath, File savePath, long revision) throws Exception { // 删除已有 FileUtils.deleteQuietly(savePath); // 创建上级目录 savePath.getParentFile().mkdirs(); // 创建目标文件 savePath.createNewFile(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileOutputStream fos = new FileOutputStream(savePath); try { repository.getFile(remotePath, revision, null, baos); baos.writeTo(fos); } finally { if (fos != null) { fos.close(); } if (baos != null) { baos.close(); } } }
private boolean saveToPath(File file, Bitmap bitmap) { boolean isSuccess = true; try { if (file.exists()) return true; // bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] imageInByte = stream.toByteArray(); long length = imageInByte.length; com.netease.vendor.util.log.LogUtil.vendor("length=" + length); if (MIN_IMAGE_SIZE >= length) { stream.close(); return false; } FileOutputStream fos = new FileOutputStream(file); stream.writeTo(fos); fos.flush(); stream.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); isSuccess = false; } return isSuccess; }
public void run() { byte[] tmp = new byte[10000]; int read; try { FileInputStream fis = new FileInputStream(fileToSend.getFile()); read = fis.read(tmp); while (read != -1) { baos.write(tmp, 0, read); read = fis.read(tmp); System.out.println(read); } fis.close(); baos.writeTo(sWriter); sWriter.flush(); baos.flush(); baos.close(); System.out.println("fileSent"); } catch (IOException e) { e.printStackTrace(); } finally { this.closeSocket(); } }
/** * generate PDF file containing all site participant * * @param data */ public void print_participant(String siteId) { HttpServletResponse res = (HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); res.addHeader("Content-Disposition", "inline; filename=\"participants.pdf\""); res.setContentType("application/pdf"); Document document = docBuilder.newDocument(); // get the participant xml document generateParticipantXMLDocument(document, siteId); generatePDF(document, outByteStream); res.setContentLength(outByteStream.size()); if (outByteStream.size() > 0) { // Increase the buffer size for more speed. res.setBufferSize(outByteStream.size()); } /* // output xml for debugging purpose try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (Exception e) { }*/ OutputStream out = null; try { out = res.getOutputStream(); if (outByteStream.size() > 0) { outByteStream.writeTo(out); } res.setHeader("Refresh", "0"); out.flush(); out.close(); } catch (Throwable ignore) { } finally { if (out != null) { try { out.close(); } catch (Throwable ignore) { } } } }
private boolean put(ByteArrayOutputStream id, InputStream in, int level) throws IOException { if (level > 0) { ByteArrayOutputStream id2 = new ByteArrayOutputStream(); while (true) { boolean eof = put(id2, in, level - 1); if (id2.size() > maxBlockSize / 2) { id2 = putIndirectId(id2); id2.writeTo(id); return eof; } else if (eof) { id2.writeTo(id); return true; } } } byte[] readBuffer = nextBuffer.getAndSet(null); if (readBuffer == null) { readBuffer = new byte[maxBlockSize]; } byte[] buff = read(in, readBuffer); if (buff != readBuffer) { // re-use the buffer if the result was shorter nextBuffer.set(readBuffer); } int len = buff.length; if (len == 0) { return true; } boolean eof = len < maxBlockSize; if (len < minBlockSize) { // in-place: 0, len (int), data id.write(0); DataUtils.writeVarInt(id, len); id.write(buff); } else { // block: 1, len (int), blockId (long) id.write(1); DataUtils.writeVarInt(id, len); DataUtils.writeVarLong(id, writeBlock(buff)); } return eof; }
/** * Write the given temporary OutputStream to the HTTP response. * * @param response current HTTP response * @param baos the temporary OutputStream to write * @throws IOException if writing/flushing failed */ protected void writeToResponse(HttpServletResponse response, ByteArrayOutputStream baos) throws IOException { // Write content type and also length (determined via byte array). response.setContentType(getContentType()); response.setContentLength(baos.size()); // Flush byte array to servlet output stream. ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); }
/** * @param pServletRequest parameter * @param pServletResponse parameter * @throws IOException exception * @throws ServletException exception */ @Override public void handleService(ServletRequest pServletRequest, ServletResponse pServletResponse) throws IOException, ServletException { final ByteArrayOutputStream pdf = new ByteArrayOutputStream(); final String deliveryId = pServletRequest.getParameter(DELIVERY_ID_PARAM); RepositoryItem orderBOItem = mOrderManager.getFactureBO(deliveryId); OutputStream out = null; if (orderBOItem != null) { RepositoryItem orderFOItem = mOrderManager.getOrderFO(orderBOItem); String profileId = (String) orderFOItem.getPropertyValue(CastoConstantesOrders.ORDER_PROPERTY_PROFILEID); String currProfileId = getProfileServices().getCurrentProfileId(); if (!currProfileId.equalsIgnoreCase(profileId)) { if (isLoggingError()) { logError( "Facture with id=" + deliveryId + " doesn't belong to profile with id=" + currProfileId); } return; } Map params = new HashMap(); params.put( "url", pServletRequest.getScheme() + "://" + pServletRequest.getServerName() + ":" + pServletRequest.getServerPort()); try { PrintPdfHelper.getInstance().generateInvoicePdf(pdf, orderBOItem, params, mCountryList); // Set header pServletResponse.setContentType(CONTENT_TYPE_PDF); pServletResponse.setContentLength(pdf.size()); out = pServletResponse.getOutputStream(); pdf.writeTo(out); out.flush(); } catch (IOException e) { logError(e); } finally { if (out != null) { out.close(); } } } else { logError("Facture with id=" + deliveryId + " was not found."); } // end if-else }
public void convert() { OutputStream os = ReportUtilXls.RemoveEmptyCells("src/test/resources/reports/excelPoiTest.xls"); OutputStream outputStreamProcessed; try { outputStreamProcessed = new FileOutputStream("src/test/resources/reports/excelPoiResult.xls"); ((ByteArrayOutputStream) os).writeTo(outputStreamProcessed); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void writeTo(OutputStream out) throws IOException { if (this.buffer != null) { MemoryInputStream mis = new MemoryInputStream(this.buffer); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (mis.available() > 0) { baos.write(mis.read()); } baos.writeTo(out); } else { System.err.println("buffer is null"); } }
public static void merge(List<String> files, String directory, String mergedFileName) throws Exception { try { ByteArrayOutputStream boas = new ByteArrayOutputStream(); MergePDFs.concatPDFs(files, boas, directory); FileOutputStream fos = new FileOutputStream(new File(directory + mergedFileName)); boas.writeTo(fos); } catch (Exception e) { logger.error(e, e); throw e; } }
/** Public API - writes this Frame to the given DataOutputStream */ public void writeTo(DataOutputStream os) throws IOException { os.writeByte(type); os.writeShort(channel); if (accumulator != null) { os.writeInt(accumulator.size()); accumulator.writeTo(os); } else { os.writeInt(payload.length); os.write(payload); } os.write(AMQP.FRAME_END); }
@Override public void write(Cell cell) throws IOException { if (encryptor == null) { super.write(cell); return; } byte[] iv = nextIv(); encryptor.setIv(iv); encryptor.reset(); // TODO: Check if this is a cell for an encrypted CF. If not, we can // write a 0 here to signal an unwrapped cell and just dump the KV bytes // afterward StreamUtils.writeRawVInt32(out, iv.length); out.write(iv); // TODO: Add support for WAL compression ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream cout = encryptor.createEncryptionStream(baos); int tlen = cell.getTagsLength(); // Write the KeyValue infrastructure as VInts. StreamUtils.writeRawVInt32(cout, KeyValueUtil.keyLength(cell)); StreamUtils.writeRawVInt32(cout, cell.getValueLength()); // To support tags StreamUtils.writeRawVInt32(cout, tlen); // Write row, qualifier, and family StreamUtils.writeRawVInt32(cout, cell.getRowLength()); cout.write(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()); StreamUtils.writeRawVInt32(cout, cell.getFamilyLength()); cout.write(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()); StreamUtils.writeRawVInt32(cout, cell.getQualifierLength()); cout.write(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()); // Write the rest ie. ts, type, value and tags parts StreamUtils.writeLong(cout, cell.getTimestamp()); cout.write(cell.getTypeByte()); cout.write(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); if (tlen > 0) { cout.write(cell.getTagsArray(), cell.getTagsOffset(), tlen); } cout.close(); StreamUtils.writeRawVInt32(out, baos.size()); baos.writeTo(out); // Increment IV given the final payload length incrementIv(baos.size()); }
private void sendPacket(String outMessage) throws SeedSorterException, ChipperNotRunningException { System.out.println("Mock Chipper - sending packet to client: " + outMessage); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); byteOut.write(outMessage.getBytes(), 0, outMessage.length()); try { byteOut.writeTo(clientSocket.getOutputStream()); byteOut.flush(); } catch (IOException e) { e.printStackTrace(); throw new SeedSorterException("-- sendPacket() - I/O error", e); } }
private void flushRaw() throws IOException { if (currentRaw != null && currentRaw.size() > 0) { if (mode == Mode.Block) { output.writeInt(-1); } System.err.println("Writing raw chunk : " + currentRaw.size()); rawChunks += currentRaw.size(); output.writeInt(currentRaw.size()); currentRaw.writeTo(output); mode = Mode.Raw; } currentRaw = null; }
static void tile(int z, int dxy, int xn, int yn) throws Exception { trans = new PNGTranscoder(); trans.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(256)); trans.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(256)); trans.addTranscodingHint( PNGTranscoder.KEY_AOI, new Rectangle(256 + (xn * dxy), 256 + (yn * dxy), dxy, dxy)); String svgURI = new File(srcdir + xtile + "-" + ytile + "-" + z + ".svg").toURI().toURL().toString(); TranscoderInput input = new TranscoderInput(svgURI); ByteArrayOutputStream bos = new ByteArrayOutputStream(); TranscoderOutput output = new TranscoderOutput(bos); try { trans.transcode(input, output); if (bos.size() > 446) { int scale = (int) Math.pow(2, z - 12); int xdir = (scale * xtile) + xn; int ynam = (scale * ytile) + yn; String dstnam = dstdir + z + "/" + xdir + "/" + ynam + ".png"; deletes.remove(dstnam); send.add("put " + dstnam + " tiles/" + z + "/" + xdir + "/" + ynam + ".png"); File ofile = new File(dstdir + "/" + z + "/" + xdir + "/"); ofile.mkdirs(); OutputStream ostream = new FileOutputStream(dstdir + "/" + z + "/" + xdir + "/" + ynam + ".png"); bos.writeTo(ostream); ostream.flush(); ostream.close(); if (send.size() > 10) { PrintWriter writer = new PrintWriter(srcdir + z + "-" + xdir + "-" + ynam + ".send", "UTF-8"); for (String str : send) { writer.println(str); } writer.close(); send = new ArrayList<String>(); } } } catch (Exception e) { System.err.println("TranscoderException: " + z + " " + xn + " " + yn); } if ((z < 18) && ((z < 16) || (bos.size() > 446))) { for (int x = 0; x < 2; x++) { for (int y = 0; y < 2; y++) { tile((z + 1), (dxy / 2), (xn * 2 + x), (yn * 2 + y)); } } } }
private void pageToFileStream() throws IOException { flush(); ByteArrayOutputStream bout = (ByteArrayOutputStream) currentStream; tempFile = FileUtil.createTempFile("cos", ".tmp", strategy.getSpoolDirectory()); LOG.trace("Creating temporary stream cache file: {}", tempFile); try { currentStream = createOutputStream(tempFile); bout.writeTo(currentStream); } finally { // ensure flag is flipped to file based inMemory = false; } }
private void headers( boolean outFinished, int streamId, int priority, List<String> nameValueBlock) throws IOException { hpackBuffer.reset(); hpackWriter.writeHeaders(nameValueBlock); int type = TYPE_HEADERS; // TODO: implement CONTINUATION int length = hpackBuffer.size(); int flags = FLAG_END_HEADERS; if (outFinished) flags |= FLAG_END_STREAM; if (priority != -1) flags |= FLAG_PRIORITY; out.writeInt((length & 0xffff) << 16 | (type & 0xff) << 8 | (flags & 0xff)); out.writeInt(streamId & 0x7fffffff); if (priority != -1) out.writeInt(priority & 0x7fffffff); hpackBuffer.writeTo(out); }
/** * Writes the clob data in the given input Reader to an external lob export file, and return it's * location information in the file as string. Location information is written in the main export * file. * * @param ir Reader that contains a clob column data. * @return Location where the column data written in the external file. * @exception Exception if any error occurs while writing the data. */ String writeCharColumnToExternalFile(Reader ir) throws Exception { // read data from the input stream and write it to // the lob export file and also calculate the amount // of data written in bytes. long clobSize = 0; int noChars = 0; if (ir != null) { noChars = ir.read(charBuf); while (noChars != -1) { // characters data is converted to bytes using // the user specified code set. lobByteArrayStream.reset(); lobCharStream.write(charBuf, 0, noChars); lobCharStream.flush(); clobSize += lobByteArrayStream.size(); lobByteArrayStream.writeTo(lobOutBinaryStream); noChars = ir.read(charBuf); } // close the input reader. ir.close(); // flush the output binary stream. lobOutBinaryStream.flush(); } else { // reader is null, the column value must be SQL NULL. // set the size to -1, on import columns will // be interepreted as NULL, filename and offset are // ignored. clobSize = -1; } // Encode this lob location information as string. This will // be written to the main export file. It will be used // to retrive this blob data on import. // Format is : <code > <fileName>.<lobOffset>.<size of lob>/ </code>. // For a NULL blob, size will be written as -1 String lobLocation = lobsFileName + "." + lobFileOffset + "." + clobSize + "/"; // update the offset, this will be where next // large object data will be written. if (clobSize != -1) lobFileOffset += clobSize; return lobLocation; }
protected void writeFile( boolean isDirectory, InputStream inputFile, String filename, boolean verbose) throws IOException { if (writtenItems.contains(filename)) { if (verbose) { String msg = MessageFormat.format( Messages.getString("Creator.Ignoring"), // $NON-NLS-1$ new Object[] {filename}); System.err.println(msg); } return; } ByteArrayOutputStream out = new ByteArrayOutputStream(); CRC32 crc = new CRC32(); long size; if (isDirectory) { size = 0; } else { size = copyFile(crc, inputFile, out); } ZipEntry entry = new ZipEntry(filename); entry.setCrc(crc.getValue()); entry.setSize(size); outputStream.putNextEntry(entry); out.writeTo(outputStream); outputStream.closeEntry(); writtenItems.add(filename); if (verbose) { long csize = entry.getCompressedSize(); long perc; if (size == 0) perc = 0; else perc = 100 - (100 * csize) / size; String msg = MessageFormat.format( Messages.getString("Creator.Adding"), // $NON-NLS-1$ new Object[] { filename, Long.valueOf(size), Long.valueOf(entry.getSize()), Long.valueOf(perc) }); System.err.println(msg); } }
/** * 导出 excel * * @param context */ @SuppressWarnings("unchecked") public void activitiesStatisitceTotalExcel(Context context) { List<Map> activitTotalList = null; Map content = new HashMap(); try { if (context.contextMap.get("startDate") == null) { context.contextMap.put("startDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date())); } String year = context.contextMap.get("startDate").toString(); content.put("year", year.substring(0, 4) + "年"); activitTotalList = (List<Map>) ((DataWrap) DataAccessor.query( "activitiesLog.activitiesStatisticsTotal", context.contextMap, DataAccessor.RS_TYPE.PAGED)) .getRs(); } catch (Exception e1) { e1.printStackTrace(); LogPrint.getLogStackTrace(e1, logger); } content.put("activitTotalList", activitTotalList); ByteArrayOutputStream baos = null; String strFileName = "每日业务活动统计表(" + DataUtil.StringUtil(context.contextMap.get("date")) + ").xls"; ActivitiesStatisticTotalExcel activitiesStatisticTotalExcel = new ActivitiesStatisticTotalExcel(); activitiesStatisticTotalExcel.createexl(); baos = activitiesStatisticTotalExcel.exportactivitTotalExcel(content); context.response.setContentType("application/vnd.ms-excel;charset=GB2312"); try { context.response.setHeader( "Content-Disposition", "attachment;filename=" + new String(strFileName.getBytes("GBK"), "ISO-8859-1")); ServletOutputStream out1 = context.response.getOutputStream(); activitiesStatisticTotalExcel.close(); baos.writeTo(out1); out1.flush(); } catch (Exception e) { e.printStackTrace(); LogPrint.getLogStackTrace(e, logger); } }
/** * 设置编码方式,保存文件内容 * * @param fileName 文件名 * @param fileContent 文件内容 * @param charset 字符集 */ public static void saveFileContent(String fileName, Object fileContent, String charset) { BufferedOutputStream bosFile = null; try { // 创建失败 createFilePath(fileName); // 创建成功 bosFile = new BufferedOutputStream(new FileOutputStream(fileName)); // 判断传入的对象类型 如果是String 则直接保存 其他的则认为是JAXB对象 if (fileContent instanceof String) { bosFile.write( null == charset ? fileContent.toString().getBytes() : fileContent.toString().getBytes(charset)); } // 如果是流文件 else if (fileContent instanceof ByteArrayOutputStream) { ((ByteArrayOutputStream) fileContent).writeTo(bosFile); // } // JAXB对象 // else // if(fileContent.getClass().isAnnotationPresent(XmlRootElement.class)){ // ByteArrayOutputStream xmlbyteos = // marshall(fileContent.getClass(), fileContent); // xmlbyteos.writeTo(bosFile); } else { } bosFile.close(); if (RemexConstants.logger.isDebugEnabled()) { StringBuilder msg = new StringBuilder("文件保存成功,路径:【").append(fileName).append("】"); RemexConstants.logger.debug(msg); } } catch (Exception e) { String msg = new StringBuilder("保存报文失败!报文路径是:").append(fileName).toString(); RemexConstants.logger.error(msg, e); throw new RIOException(msg, e); } finally { if (bosFile != null) { try { bosFile.close(); } catch (IOException e) { RemexConstants.logger.error(e); } } } }