List of usage examples for java.io BufferedReader ready
public boolean ready() throws IOException
From source file:com.meltmedia.cadmium.email.jersey.EmailResource.java
public String readFromFile(String fileName) { String content = null;//w w w . j a v a 2 s.c om BufferedReader br = null; try { File inFile = new File(fileName); br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile))); content = ""; while (br.ready()) { content += br.readLine(); } br.close(); } catch (FileNotFoundException ex) { log.error("Failed to find file.", ex); } catch (IOException ex) { log.error("Failed to read file.", ex); } finally { if (br != null) { try { br.close(); } catch (Exception e) { } } } return content; }
From source file:name.milesparker.gerrit.analysis.SimpleFileConverter.java
protected void convert(File file) throws FileNotFoundException, IOException { Path path = new Path(file.getAbsolutePath()); if (!file.isDirectory() && path.getFileExtension() == null) { return;//from www . ja v a 2 s.com } for (String ext : ignoreExtension) { if (StringUtils.equals(ext, path.getFileExtension())) { return; } } if (file.exists()) { if (file.isDirectory()) { for (File member : file.listFiles()) { convert(member); } } else { if (path.getFileExtension() == null) { return; } if (path.getFileExtension().equals(extension)) { log(" " + file.getAbsolutePath()); filesConverted++; BufferedReader br = new BufferedReader(new FileReader(file)); StringBuilder fileContents = new StringBuilder(8000); int lineNum = 0; while (br.ready()) { String line = br.readLine(); String convert = convertLine(line); fileContents.append(convert + "\n"); if (!line.equals(convert)) { String lineNumString = StringUtils.leftPad(lineNum + "", 5); log(" " + lineNumString + ": " + line + "\n " + convert); } lineNum++; } br.close(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); String convertString = convertFile(fileContents.toString()); writer.write(convertString); writer.close(); } } } monitor.worked(1); }
From source file:org.jboss.maven.plugins.qstools.checkers.ReadmeChecker.java
/** * Check if the file contains all defined metadata */// w w w . j ava 2s .c om private void checkReadmeFile(String groupId, File readme, Map<String, List<Violation>> results) throws IOException { Map<String, String> metadatas = getConfigurationProvider().getQuickstartsRules(groupId) .getReadmeMetadatas(); BufferedReader br = new BufferedReader(new FileReader(readme)); try { Pattern p = Pattern.compile(regexPattern); List<String> usedPatterns = new ArrayList<String>(); Map<String, String> usedValues = new HashMap<String, String>(); while (br.ready()) { String line = br.readLine(); Matcher m = p.matcher(line); if (m.find()) { usedPatterns.add(m.group()); usedValues.put(m.group(), StringUtils.stripStart(line.substring(m.group().length(), line.length()), " ")); } } for (String metadataRaw : metadatas.keySet()) { String metadata = metadataRaw.replace("FOLDER-NAME", folderName); if (usedPatterns.contains(metadata)) { String value = usedValues.get(metadata); String expected = metadatas.get(metadataRaw); if (!value.matches(expected)) { String msg = "Content for metadata [%s = %s] should follow the [%s] pattern"; addViolation(readme, results, 0, String.format(msg, metadata, value, expected)); } } else { String msg = "File doesn't contain [%s] metadata"; addViolation(readme, results, 3, String.format(msg, metadata)); } } if (!usedPatterns.contains(folderName)) { String msg = "Readme title doesn't match the folder name: " + folderName; addViolation(readme, results, 1, msg); } } finally { if (br != null) { br.close(); } } }
From source file:ubic.gemma.apps.ArrayDesignSequenceManipulatingCli.java
/** * @param fileName/*from ww w.j av a 2 s . co m*/ * @return * @throws IOException */ private Collection<String> readListFileToStrings(String fileName) throws IOException { Collection<String> eeNames = new HashSet<String>(); BufferedReader in = new BufferedReader(new FileReader(fileName)); while (in.ready()) { String eeName = in.readLine().trim(); if (eeName.startsWith("#")) { continue; } eeNames.add(eeName); } return eeNames; }
From source file:org.apache.streams.gnip.facebook.test.FacebookEDCSerDeTest.java
@Test public void Tests() throws Exception { xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE); xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE); xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE); InputStream is = FacebookEDCSerDeTest.class.getResourceAsStream("/FacebookEDC.xml"); if (is == null) System.out.println("null"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE); xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE); xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE); try {//from ww w.j a v a 2 s . co m while (br.ready()) { String line = br.readLine(); LOGGER.debug(line); Entry xmlObject = xmlMapper.readValue(line, Entry.class); String xml = xmlMapper.writeValueAsString(xmlObject); } } catch (Exception e) { LOGGER.error(e.getMessage()); Assert.fail(); } }
From source file:com.pl.plugins.commons.dal.utils.reports.JasperReportService.java
private String getXMLTemplate(String reportTemplateFileName) { String fileName = reportTemplateFolder + "/" + reportTemplateFileName; BufferedReader in; String template = ""; try {//from w w w . ja v a 2 s.co m in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); while (in.ready()) { template += in.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return template; }
From source file:de.gesundkrank.wikipedia.hadoop.parser.Parser.java
private void readNextPage(BufferedReader in) throws IOException { resetPageMarkers();//from w w w . jav a 2 s .c om currentPage = new WikiPageWritable(); while (in.ready()) { String line = in.readLine(); if (readPageTitle(line) || readPageId(line) || readPageRedirect(line)) { continue; } //revision if (matchRevision(line)) { break; } Matcher pageEndMatcher = PAGE_END_PATTERN.matcher(line); if (pageEndMatcher.matches()) { break; } } }
From source file:edu.du.penrose.systems.fedoraApp.util.MetsBatchFileSplitter.java
/** * Split a file with multiple METS sections into separate files each containing * a single METS record. The input file must contain one or more multiple * <mets></mets> elements (sections). if true a OBJID must exist in every <mets> * element, this will become the file name. Otherwise a unique file name is * generated. Return true if the <batch update="true"> is set in the batch file other * wise return false (defaults to new file being ingested ). * //from ww w . j av a2s . co m * @see edu.du.penrose.systems.fedoraApp.batchIngest.bus.BatchIngestThreadManager#setBatchSetStatus(String, String) * @param threadStatus this object receives status updates while splitting the file. * @param inFile file to split * @param metsNewDirectory directory containing METS for new objects. * @param metsUpdatesDirectory directory containing METS for existing objects. * @param nameFileFromOBJID if true a OBJID must exist in every <mets> element, this will become the file name. Otherwise a unique file name is * generated * @deprecated * @throws Exception on any IO error. */ static public void splitMetsBatchFile_version_1(BatchIngestOptions ingestOptions, ThreadStatusMsg threadStatus, File inFile, String metsNewDirectory, String metsUpdatesDirectory, boolean nameFileFromOBJID) throws FatalException { String metsDirectory = null; // will get set to either the new directory or the updates directory. FileInputStream batchFileInputStream; try { batchFileInputStream = new FileInputStream(inFile); } catch (FileNotFoundException e) { throw new FatalException(e.getMessage()); } DataInputStream batchFileDataInputStream = new DataInputStream(batchFileInputStream); BufferedReader batchFileBufferedReader = new BufferedReader( new InputStreamReader(batchFileDataInputStream)); File outFile = null; FileOutputStream metsFileOutputStream = null; BufferedWriter metsBufferedWriter = null; String oneLine = null; String documentType = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; int fileCount = 0; try { while (batchFileBufferedReader.ready()) { threadStatus.setStatus("Spliting XML file #: " + fileCount); oneLine = batchFileBufferedReader.readLine(); if (oneLine.contains("<?xml version")) { documentType = oneLine; } if (oneLine.contains("<batch")) { if (oneLine.contains(FedoraAppConstants.BATCH_FILE_UPDATE_MARKER + "=" + QUOTE + "true" + QUOTE) || oneLine.contains( FedoraAppConstants.BATCH_FILE_UPDATE_MARKER + "=" + APOST + "true" + APOST)) { ingestOptions.setBatchIsUpdates(true); metsDirectory = metsUpdatesDirectory; } else { ingestOptions.setBatchIsUpdates(false); metsDirectory = metsNewDirectory; } } if (oneLine.contains("<mets:mets")) { boolean haveEntireMetsLine = false; while (!haveEntireMetsLine) { StringBuffer tempBuffer = new StringBuffer(oneLine); String moreOfMetsLine = null; if (!oneLine.contains(">")) { moreOfMetsLine = batchFileBufferedReader.readLine(); tempBuffer.append(moreOfMetsLine); if (moreOfMetsLine.contains(">")) { haveEntireMetsLine = true; oneLine = tempBuffer.toString(); } else { oneLine = tempBuffer.toString(); } } else { haveEntireMetsLine = true; } } // Name the output file for a single Mets element and its contents. if (nameFileFromOBJID) { String objID = MetsBatchFileSplitter.getObjID(oneLine); outFile = new File(metsDirectory + objID + ".xml"); logger.info("outputSplitFile METS file: " + metsDirectory + objID + ".xml"); if (outFile.exists()) { String errorMsg = "OBJID already exists:" + outFile.getName(); System.out.println(errorMsg); logger.error(errorMsg); throw new FatalException(errorMsg); } } else { outFile = new File(metsDirectory + edu.du.penrose.systems.util.FileUtil.getDateTimeMilliSecondEnsureUnique() + ".xml"); } logger.info("outputSplitFile METS file: " + outFile.toString() + "\n\n"); metsFileOutputStream = new FileOutputStream(outFile); metsBufferedWriter = new BufferedWriter(new OutputStreamWriter(metsFileOutputStream, "UTF-8")); metsBufferedWriter.write(documentType); metsBufferedWriter.newLine(); // This is a version 1 batch file, so write a default version 2 command line for the new ingester metsBufferedWriter.write(FedoraAppConstants.VERSION_ONE_COMMAND_LINE); metsBufferedWriter.newLine(); while (!oneLine.contains("</mets:mets")) { // null pointer on premature end of file. metsBufferedWriter.write(oneLine); metsBufferedWriter.newLine(); oneLine = batchFileBufferedReader.readLine(); } metsBufferedWriter.write(oneLine); metsBufferedWriter.newLine(); metsBufferedWriter.close(); fileCount++; } } // while } catch (NullPointerException e) { String errorMsg = "Unable to split files, Permature end of file: Corrupt:" + inFile.toString() + " ?"; throw new FatalException(errorMsg); } catch (Exception e) { String errorMsg = "Unable to split files: " + e.getMessage(); logger.fatal(errorMsg); throw new FatalException(errorMsg); } finally { try { if (batchFileBufferedReader != null) { batchFileBufferedReader.close(); } if (metsBufferedWriter != null) { metsBufferedWriter.close(); } } catch (IOException e) { throw new FatalException(e.getMessage()); } } }
From source file:gestionale.persistence.DAOCliente.java
public String numeroAvvii() { File file = new File("License.txt"); String leggi = null;//from w w w . j ava 2s . com try { BufferedReader br = new BufferedReader(new FileReader(file)); try { if (br.ready()) { try { leggi = br.readLine(); //logger.info("NumeroAvvii: " + numeroAvvii); br.close(); } catch (IOException ex) { logger.info("IOException: " + ex.getMessage()); } } } catch (IOException ex) { logger.info("IOException in secnodo catch: " + ex.getMessage()); } } catch (FileNotFoundException ex) { logger.info("FileNotFoundException: " + ex.getMessage()); } return leggi; }
From source file:it.cnr.icar.eric.server.cms.CanonicalXMLValidationService.java
private void validateXMLFile(StreamSource inputSrc, Transformer transformer) throws IOException, TransformerException, RegistryException { //Create the output file with validation results File outputFile = File.createTempFile("CanonicalXMLValidationService_OutputFile", ".xml"); outputFile.deleteOnExit();//from w w w. j ava 2 s . co m if (log.isDebugEnabled()) { dumpStream(inputSrc); log.debug("Tempfile= " + outputFile.getAbsolutePath()); } StreamResult sr = new StreamResult(outputFile); transformer.transform(inputSrc, sr); @SuppressWarnings("resource") BufferedReader outputFileReader = new BufferedReader(new FileReader(outputFile)); StringBuffer sb2 = null; while (outputFileReader.ready()) { String line = outputFileReader.readLine(); if (line.indexOf("error") != -1) { // if the line has the word 'error', a validation error has occurred // obtain the message and store. There may be multiple // violations. So, loop through all, then pass to exception if (sb2 == null) { sb2 = new StringBuffer(); sb2.append(ServerResourceBundle.getInstance().getString("message.errorValidatingXML")); } // The error message SHOULD contain the key to an i18n message // in the server ResourceBundle.properties file. String key = line; try { line = ServerResourceBundle.getInstance().getString(key); } catch (MissingResourceException ex) { log.error(ServerResourceBundle.getInstance().getString("message.missingMessage", new Object[] { key })); } sb2.append(line).append(' '); } } if (sb2 != null) { throw new ValidationException(sb2.toString()); } }