List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:br.com.capanema.kers.velocity.util.BuildManagerUtil.java
/** * Increment source code of filePath using template fragment. * // w w w . j a v a2 s . c om * @param filePath * @param incrementPath * @param incrementPattern * @param dataGroup */ public static void incrementSourceCode(String filePath, String incrementPath, String incrementPattern, String firstAfter, Map<String, String> params, TemplateDataGroup dataGroup) { try { HashMap<String, Object> velocityVariables = new HashMap<String, Object>(); //map for velocity variables velocityVariables.put("data", dataGroup); //conjunto de vriaveis que podem ser usados no template if (params != null && params.size() > 0) { /* for (String name : params.keySet()) { velocityVariables.put("params."+name, params.get(name)); }*/ velocityVariables.put("params", params); } //rodando velocity do incremento TemplateEngine templateEngine = TemplateEngineFactory.getEngine(incrementPath, true); String incrementSource = templateEngine.runFile(incrementPath, velocityVariables); // Create the pattern Pattern pattern = Pattern.compile("[\r\n]*[\t]*" + incrementPattern, Pattern.DOTALL); //o "[\r\n]*" para pegar as quebras de linhas que podem existir no incremento Matcher matcher = pattern.matcher(""); //novo incremento //aqui vai executar o pattern no prprio incremento... se o pattern estiver errado no ir encontrar nada e vai abortar o incremento matcher.reset(incrementSource); Map<String, String[]> mapGroupIncrement = new LinkedHashMap<String, String[]>(); while (matcher.find()) { String[] groups = new String[matcher.groupCount()]; for (int i = 0; i < matcher.groupCount(); i++) { groups[i] = matcher.group(i + 1); } String increment = matcher.group(); //new increment mapGroupIncrement.put(increment, groups); //map increment vs groups } if (mapGroupIncrement.size() == 0) { //no encontrou groups no incremento (usado para as comparaes), aborta return; } //le o arquivo atual FileInputStream inputFilePath = new FileInputStream(filePath); BufferedInputStream bufferedInput = new BufferedInputStream(inputFilePath); StringBuffer filePathContent = new StringBuffer(); int ch = 0; while ((ch = bufferedInput.read()) > -1) { filePathContent.append((char) ch); } inputFilePath.close(); bufferedInput.close(); //procura no arquivo todo pela expresso regular matcher = pattern.matcher(""); matcher.reset(filePathContent); StringBuffer newContentFile = new StringBuffer(); int countMatcher = 0; Map<String, String[]> mapGroupFile = new HashMap<String, String[]>(); while (matcher.find()) { //verifica cada ocorrncia da expresso no arquivo String[] groups = new String[matcher.groupCount()]; //pega os groups "()" do matcher para fazer a comparao com os groups do incremento que est sendo gerado for (int i = 0; i < matcher.groupCount(); i++) { groups[i] = matcher.group(i + 1); } mapGroupFile.put(matcher.group(), groups); //adiciona esse group em uma lista para ser avaliado depois countMatcher++; //isso vai contar onde esta o ltimo matcher } //valida quais incrementos so realmente novos, comparando os groups List<String> newIncrements = new LinkedList<String>(); for (String groupIncrement : mapGroupIncrement.keySet()) { String[] groups1 = mapGroupIncrement.get(groupIncrement); //groups do incremento boolean itemFound = false; for (String groupFile : mapGroupFile.keySet()) { String[] groups2 = mapGroupFile.get(groupFile); //groups do incremento if (ArrayUtil.equals(groups1, groups2)) { //se no arquivo tem o cdigo que est sendo gerado, no precisa adicionar esse incremnto itemFound = true; } } if (!itemFound) { //se no arquivo no tem o cdigo que est sendo gerado, adiciona em um array newIncrements.add(groupIncrement); } } //realiza uma quebra de linha adicional para o primeiro item do incremento, para no ficar na mesma linha do ltimo matcher no arquivo StringBuffer newIncrementSource = new StringBuffer(); int i = 0; for (String incremento : newIncrements) { if (i == 0 && incremento.indexOf("\r\n\r\n") != 0) { //s coloca quebra de linha se precisar newIncrementSource.append("\r\n"); } newIncrementSource.append(incremento); i++; } if (newIncrements.size() > 0) { //no encontrou nenhum increment no arquivo, ento procura pelo firstAfter para inserir o primeiro incremento if (countMatcher == 0 && firstAfter != null && !firstAfter.equals("")) { pattern = Pattern.compile(firstAfter, Pattern.DOTALL); matcher = pattern.matcher(""); matcher.reset(filePathContent); //esse loop s serviu para contar e achar o ltimo matcher. No consegui fazer sem isso :( countMatcher = 0; while (matcher.find()) { //verifica cada ocorrncia da expresso countMatcher++; } } //aqui vou realmente substituir os valores, j sabendo qual a ltima ocorrencia da palavra no arquivo i = 0; matcher.reset(); while (matcher.find()) { //verifica cada ocorrncia da expresso i++; if (countMatcher == i) { //se encontrou a ltima ocorrencia String matcherGroup = matcher.group(); matcher.appendReplacement(newContentFile, matcherGroup + newIncrementSource); //substitui a ultima ocorrencia do firstIncrement } } matcher.appendTail(newContentFile); } //save new file if (newContentFile.length() > 0) { FileUtil.writeFile(filePath, newContentFile.toString()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
From source file:riddimon.android.asianetautologin.HttpUtils.java
public static String readStreamIntoString(InputStream in) { StringBuilder builder = new StringBuilder(); int buf_size = 50 * 1024; // read in chunks of 50 KB ByteArrayBuffer bab = new ByteArrayBuffer(buf_size); int read = 0; BufferedInputStream bis = new BufferedInputStream(in); if (bis != null) { byte buffer[] = new byte[buf_size]; try {/*from www . j a v a2 s.co m*/ while ((read = bis.read(buffer, 0, buf_size)) != -1) { //builder.append(new String(buffer, "utf-8")); bab.append(buffer, 0, read); } builder.append(new String(bab.toByteArray(), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } return builder.toString(); }
From source file:com.ibm.amc.FileManager.java
private static void compressFile(File file, ZipOutputStream out, String basedir) { try {//from w w w . j ava 2 s.com BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); ZipEntry entry = new ZipEntry(basedir + file.getName()); out.putNextEntry(entry); int length = Long.valueOf(file.length()).intValue(); int buffer = ZIP_BUFFER; if (length != 0) { buffer = length; } int count; byte data[] = new byte[buffer]; while ((count = bis.read(data, 0, buffer)) != -1) { out.write(data, 0, count); } bis.close(); } catch (Exception e) { throw new AmcRuntimeException(e); } }
From source file:com.eviware.soapui.support.Tools.java
public static int copyFile(File source, File target, boolean overwrite) throws IOException { int bytes = 0; if (target.exists()) { if (overwrite) { target.delete();//from w w w.j av a 2 s . co m } else { return -1; } } else { String path = target.getAbsolutePath(); int ix = path.lastIndexOf(File.separatorChar); if (ix != -1) { path = path.substring(0, ix); File pathFile = new File(path); if (!pathFile.exists()) { pathFile.mkdirs(); } } } BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); int read = in.read(copyBuffer); while (read != -1) { if (read > 0) { out.write(copyBuffer, 0, read); bytes += read; } read = in.read(copyBuffer); } in.close(); out.close(); return bytes; }
From source file:net.duckling.ddl.util.FileUtil.java
/** * Brief Intro Here/*from www . j a v a2 s . c o m*/ * ? * @param */ public static void copyFile(File sourceFile, File targetFile) throws IOException { // ? FileInputStream input = new FileInputStream(sourceFile); BufferedInputStream inBuff = new BufferedInputStream(input); // ? FileOutputStream output = new FileOutputStream(targetFile); BufferedOutputStream outBuff = new BufferedOutputStream(output); // byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // ? outBuff.flush(); // ? inBuff.close(); outBuff.close(); output.close(); input.close(); }
From source file:egovframework.oe1.cms.com.service.EgovOe1Properties.java
/** * ?? ?? ?? Key ? ? //from w ww . j ava 2 s . co m * * @param ?? * @param ??? * ? ? Key * @return ?? ?? Key ? */ public static String getProperty(String fileName, String key) { FileInputStream fis = null; java.io.BufferedInputStream bis = null; try { java.util.Properties props = new java.util.Properties(); String file1 = fileName.replace('\\', FILE_SEPARATOR).replace('/', FILE_SEPARATOR); fis = new FileInputStream(file1); bis = new java.io.BufferedInputStream(fis); props.load(bis); String value = props.getProperty(key); return value; } catch (java.io.FileNotFoundException fne) { return errCodeFnfe; } catch (java.io.IOException ioe) { return errCodeIoe; } finally { if (fis != null) try { fis.close(); } catch (Exception e) { debug(e); } if (bis != null) try { bis.close(); } catch (Exception e) { debug(e); } } }
From source file:Main.java
public static boolean downloadFile(File file, URL url) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; HttpURLConnection conn = null; try {// ww w . j a v a 2 s . c om conn = (HttpURLConnection) url.openConnection(); bis = new BufferedInputStream(conn.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(file)); int contentLength = conn.getContentLength(); byte[] buffer = new byte[BUFFER_SIZE]; int read = 0; int count = 0; while ((read = bis.read(buffer)) != -1) { bos.write(buffer, 0, read); count += read; } if (count < contentLength) return false; int responseCode = conn.getResponseCode(); if (responseCode / 100 != 2) { // error return false; } // finished return true; } finally { try { bis.close(); bos.close(); conn.disconnect(); } catch (Exception e) { } } }
From source file:com.glaf.core.util.FileUtils.java
public static void save(String filename, InputStream inputStream) { if (filename == null || inputStream == null) { return;//from w ww. j a v a2s.c o m } String path = ""; String sp = System.getProperty("file.separator"); if (filename.indexOf(sp) != -1) { path = filename.substring(0, filename.lastIndexOf(sp)); } if (filename.indexOf("/") != -1) { path = filename.substring(0, filename.lastIndexOf("/")); } path = getJavaFileSystemPath(path); java.io.File dir = new java.io.File(path + sp); mkdirsWithExistsCheck(dir); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(inputStream); bos = new BufferedOutputStream(new FileOutputStream(filename)); int bytesRead = 0; byte[] buffer = new byte[BUFFER_SIZE]; while ((bytesRead = bis.read(buffer, 0, BUFFER_SIZE)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); bis.close(); bos.close(); bis = null; bos = null; } catch (IOException ex) { bis = null; bos = null; throw new RuntimeException(ex); } finally { try { if (bis != null) { bis.close(); bis = null; } if (bos != null) { bos.close(); bos = null; } } catch (IOException ioe) { } } }
From source file:com.depas.utils.FileUtils.java
/** * Returns content of resource that exists on classpath *///ww w.j ava 2 s. c om public static String getTextFromResource(String resourceName) throws IOException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl.getResource(resourceName) == null) { throw new FileNotFoundException( "The resource " + resourceName + " could not be found on the current classpath."); } StringBuffer buf = new StringBuffer(); BufferedInputStream bis = null; try { InputStream is = cl.getResourceAsStream(resourceName); bis = new BufferedInputStream(is); int i; while ((i = bis.read()) != -1) { buf.append((char) i); } } finally { try { bis.close(); } catch (Exception ex) { } } return buf.toString(); }
From source file:com.ibm.amc.FileManager.java
public static File decompress(URI temporaryFileUri) { final File destination = new File(getUploadDirectory(), temporaryFileUri.getSchemeSpecificPart()); if (!destination.mkdirs()) { throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED", destination.getPath());//w w w .j ava 2 s .c o m } ZipFile zipFile = null; try { zipFile = new ZipFile(getFileForUri(temporaryFileUri)); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File newDirOrFile = new File(destination, entry.getName()); if (newDirOrFile.getParentFile() != null && !newDirOrFile.getParentFile().exists()) { if (!newDirOrFile.getParentFile().mkdirs()) { throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getParentFile().getPath()); } } if (entry.isDirectory()) { if (!newDirOrFile.mkdir()) { throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getPath()); } } else { BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int size; byte[] buffer = new byte[ZIP_BUFFER]; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newDirOrFile), ZIP_BUFFER); while ((size = bis.read(buffer, 0, ZIP_BUFFER)) != -1) { bos.write(buffer, 0, size); } bos.flush(); bos.close(); bis.close(); } } } catch (Exception e) { throw new AmcRuntimeException(e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { logger.debug("decompress", "close failed with " + e); } } } return destination; }