List of usage examples for java.io FileInputStream read
public int read(byte b[]) throws IOException
b.length
bytes of data from this input stream into an array of bytes. From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
@SuppressWarnings("unchecked") protected static void addSignatureToPDF(byte[] pdf, byte[] signature) throws Exception { PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 128000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG);//from w w w . j av a2s. c o m dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
@SuppressWarnings("unchecked") protected static void main(String[] args) throws Exception { byte[] pdf;//from w w w . j a v a 2 s .co m { File f = new File("c:/trabalhos/java/teste.pdf"); FileInputStream fin = new FileInputStream(f); pdf = new byte[(int) f.length()]; fin.read(pdf); fin.close(); } PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 256000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.setSignDate(Calendar.getInstance()); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); byte[] signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }
From source file:com.aurel.track.lucene.util.FileUtil.java
private static void zipFiles(File dirZip, ZipOutputStream zipOut, String rootPath) { try {/*from w w w . ja v a 2 s . com*/ // get a listing of the directory content File[] dirList = dirZip.listFiles(); byte[] readBuffer = new byte[2156]; int bytesIn; // loop through dirList, and zip the files for (int i = 0; i < dirList.length; i++) { File f = dirList[i]; if (f.isDirectory()) { // if the File object is a directory, call this // function again to add its content recursively String filePath = f.getAbsolutePath(); zipFiles(new File(filePath), zipOut, rootPath); // loop again continue; } // if we reached here, the File object f was not a directory // create a FileInputStream on top of f FileInputStream fis = new FileInputStream(f); // create a new zip entry ZipEntry anEntry = new ZipEntry( f.getAbsolutePath().substring(rootPath.length() + 1, f.getAbsolutePath().length())); // place the zip entry in the ZipOutputStream object zipOut.putNextEntry(anEntry); // now write the content of the file to the ZipOutputStream while ((bytesIn = fis.read(readBuffer)) != -1) { zipOut.write(readBuffer, 0, bytesIn); } // close the Stream fis.close(); } } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); } }
From source file:com.nridge.core.base.std.FilUtl.java
/** * Compresses the input path name into a ZIP output file stream. The * method will recursively process all files and sub folders within * the input path file./*from w ww . j a va2 s .c o m*/ * * @param aPathName Identifies the name of the folder to compress. * @param aZipOutStream A previously opened ZIP output file stream. * @throws IOException Related to opening the file streams and * related read/write operations. */ static public void zipPath(String aPathName, ZipOutputStream aZipOutStream) throws IOException { int byteCount; byte[] ioBuf; String[] fileList; File zipFile, inFile; FileInputStream fileIn; zipFile = new File(aPathName); if (!zipFile.isDirectory()) return; fileList = zipFile.list(); if (fileList == null) return; for (String fileName : fileList) { inFile = new File(aPathName, fileName); if (inFile.isDirectory()) zipPath(inFile.getPath(), aZipOutStream); else { ioBuf = new byte[FILE_IO_BUFFER_SIZE]; fileIn = new FileInputStream(inFile); aZipOutStream.putNextEntry(new ZipEntry(inFile.getName())); byteCount = fileIn.read(ioBuf); while (byteCount > 0) { aZipOutStream.write(ioBuf, 0, byteCount); byteCount = fileIn.read(ioBuf); } fileIn.close(); } } }
From source file:io.apigee.buildTools.enterprise4g.utils.ZipUtils.java
static void addDir(File dirObj, ZipOutputStream out, File root, String prefix) throws IOException { File[] files = dirObj.listFiles(); byte[] tmpBuf = new byte[1024]; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { addDir(files[i], out, root, prefix); continue; }/*from w ww . j a v a2s. c o m*/ FileInputStream in = new FileInputStream(files[i].getAbsolutePath()); log.debug(" Adding: " + files[i].getAbsolutePath()); String relativePath = files[i].getCanonicalPath().substring(root.getCanonicalPath().length()); while (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } while (relativePath.startsWith("\\")) { relativePath = relativePath.substring(1); } String left = Matcher.quoteReplacement("\\"); String right = Matcher.quoteReplacement("/"); relativePath = relativePath.replaceAll(left, right); relativePath = (prefix == null) ? relativePath : prefix + "/" + relativePath; out.putNextEntry(new ZipEntry(relativePath)); int len; while ((len = in.read(tmpBuf)) > 0) { out.write(tmpBuf, 0, len); } out.closeEntry(); in.close(); } }
From source file:uploadProcess.java
public static boolean decrypt(File inputFolder, String fileName, String patientID, String viewKey) { try {/*from ww w . jav a2 s . c om*/ String ukey = GetKey.getPatientKey(patientID); if (viewKey.equals(ukey)) { //Download File from Cloud.. DropboxUpload download = new DropboxUpload(); download.downloadFile(fileName, StoragePath.getDropboxDir() + patientID, inputFolder); File inputFile = new File(inputFolder.getAbsolutePath() + File.separator + fileName); FileInputStream fis = new FileInputStream(inputFile); File outputFolder = new File(inputFolder.getAbsolutePath() + File.separator + "temp"); if (!outputFolder.exists()) { outputFolder.mkdir(); } FileOutputStream fos = new FileOutputStream( outputFolder.getAbsolutePath() + File.separator + fileName); byte[] k = ukey.getBytes(); SecretKeySpec key = new SecretKeySpec(k, "AES"); Cipher enc = Cipher.getInstance("AES"); enc.init(Cipher.DECRYPT_MODE, key); CipherOutputStream cos = new CipherOutputStream(fos, enc); byte[] buf = new byte[1024]; int read; while ((read = fis.read(buf)) != -1) { cos.write(buf, 0, read); } fis.close(); fos.flush(); cos.close(); return true; } else { return false; } } catch (Exception e) { System.out.println("Error: " + e); } return false; }
From source file:it.geosolutions.tools.compress.file.Compressor.java
/** * @param outputDir// www .ja va 2 s . c o m * The directory where the zipfile will be created * @param zipFileBaseName * The basename of hte zip file (i.e.: a .zip will be appended) * @param folder * The folder that will be compressed * @return The created zipfile, or null if an error occurred. * @deprecated TODO UNTESTED */ public static File deflate(final File outputDir, final String zipFileBaseName, final File folder) { // Create a buffer for reading the files byte[] buf = new byte[4096]; // Create the ZIP file final File outZipFile = new File(outputDir, zipFileBaseName + ".zip"); if (outZipFile.exists()) { if (LOGGER.isInfoEnabled()) LOGGER.info("The output file already exists: " + outZipFile); return outZipFile; } ZipOutputStream out = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(outZipFile); bos = new BufferedOutputStream(fos); out = new ZipOutputStream(bos); Collector c = new Collector(null); List<File> files = c.collect(folder); // Compress the files for (File file : files) { FileInputStream in = null; try { in = new FileInputStream(file); if (file.isDirectory()) { out.putNextEntry(new ZipEntry(Path.toRelativeFile(folder, file).getPath())); } else { // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(FilenameUtils.getBaseName(file.getName()))); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } finally { try { // Complete the entry out.closeEntry(); } catch (IOException e) { } IOUtils.closeQuietly(in); } } } catch (IOException e) { LOGGER.error(e.getLocalizedMessage(), e); return null; } finally { // Complete the ZIP file IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(out); } return outZipFile; }
From source file:it.geosolutions.tools.compress.file.Compressor.java
/** * This function zip the input file.// w ww. j a v a 2 s . co m * * @param file * The input file to be zipped. * @param out * The zip output stream. * @throws IOException */ public static void zipFile(final File file, final ZipOutputStream out) throws IOException { if (file != null && out != null) { // /////////////////////////////////////////// // Create a buffer for reading the files // /////////////////////////////////////////// byte[] buf = new byte[4096]; FileInputStream in = null; try { in = new FileInputStream(file); // ////////////////////////////////// // Add ZIP entry to output stream. // ////////////////////////////////// out.putNextEntry(new ZipEntry(FilenameUtils.getName(file.getAbsolutePath()))); // ////////////////////////////////////////////// // Transfer bytes from the file to the ZIP file // ////////////////////////////////////////////// int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // ////////////////////// // Complete the entry // ////////////////////// out.closeEntry(); } catch (IOException e) { if (LOGGER.isErrorEnabled()) LOGGER.error(e.getLocalizedMessage(), e); if (out != null) out.close(); } finally { if (in != null) in.close(); } } else throw new IOException("One or more input parameters are null!"); }
From source file:it.cnr.icar.eric.common.Utility.java
public static ZipOutputStream createZipOutputStream(String baseDir, String[] relativeFilePaths, OutputStream os) throws FileNotFoundException, IOException { if (baseDir.startsWith("file:/")) { baseDir = baseDir.substring(5);/*from ww w .j a va2 s. c om*/ } ZipOutputStream zipoutputstream = new ZipOutputStream(os); zipoutputstream.setMethod(ZipOutputStream.STORED); for (int i = 0; i < relativeFilePaths.length; i++) { File file = new File(baseDir + FILE_SEPARATOR + relativeFilePaths[i]); byte[] buffer = new byte[1000]; int n; FileInputStream fis; // Calculate the CRC-32 value. This isn't strictly necessary // for deflated entries, but it doesn't hurt. CRC32 crc32 = new CRC32(); fis = new FileInputStream(file); while ((n = fis.read(buffer)) > -1) { crc32.update(buffer, 0, n); } fis.close(); // Create a zip entry. ZipEntry zipEntry = new ZipEntry(relativeFilePaths[i]); zipEntry.setSize(file.length()); zipEntry.setTime(file.lastModified()); zipEntry.setCrc(crc32.getValue()); // Add the zip entry and associated data. zipoutputstream.putNextEntry(zipEntry); fis = new FileInputStream(file); while ((n = fis.read(buffer)) > -1) { zipoutputstream.write(buffer, 0, n); } fis.close(); zipoutputstream.closeEntry(); } return zipoutputstream; }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java
public static MimeBodyPart zipAttachment(String zipFileName, Map mailOptions, File tempFolder) { logger.debug("IN"); MimeBodyPart messageBodyPart = null; try {/*from w w w .ja v a2 s.c o m*/ String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : ""; byte[] buffer = new byte[4096]; // Create a buffer for copying int bytesRead; // the zip String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(bout); logger.debug("File zip to write: " + tempFolderPath + File.separator + "zippedFile.zip"); //files to zip String[] entries = tempFolder.list(); for (int i = 0; i < entries.length; i++) { //File f = new File(tempFolder, entries[i]); File f = new File(tempFolder + File.separator + entries[i]); if (f.isDirectory()) continue;//Ignore directory logger.debug("insert file: " + f.getName()); FileInputStream in = new FileInputStream(f); // Stream to read file ZipEntry entry = new ZipEntry(f.getName()); // Make a ZipEntry out.putNextEntry(entry); // Store entry while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip"); } catch (Exception e) { logger.error("Error while creating the zip", e); return null; } logger.debug("OUT"); return messageBodyPart; }