List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:org.commoncrawl.service.dns.DNSServiceTester.java
void startTest(File testFileLocation) { LOG.info("Starting Test..."); LOG.info("Loading DNS Test File:" + testFileLocation); JVMStats.dumpMemoryStats();/*from w ww. j av a 2 s . c om*/ FileReader reader = null; NIODNSCache cache = NIODNSLocalResolver.getDNSCache(); try { reader = new FileReader(testFileLocation); BufferedReader lineReader = new BufferedReader(reader); String line = null; HashSet<String> hostSet = new HashSet<String>(); while ((line = lineReader.readLine()) != null) { int firstDelimiterIdx = line.indexOf(",/"); int secondDelimiterIdx = -1; int thirdDelimiterIdx = -1; if (firstDelimiterIdx != -1) { secondDelimiterIdx = line.indexOf(',', firstDelimiterIdx + 2); thirdDelimiterIdx = line.indexOf(',', secondDelimiterIdx + 1); } if (firstDelimiterIdx != -1 && secondDelimiterIdx != -1) { final String hostName = line.substring(0, firstDelimiterIdx); final String ipAddress = line.substring(firstDelimiterIdx + 2, secondDelimiterIdx); int ipAddressInteger = IPAddressUtils.IPV4AddressStrToInteger(ipAddress); LOG.info("Querying Service for Address for Host:" + hostName); DNSQueryInfo queryInfo = new DNSQueryInfo(); queryInfo.setHostName(hostName); // increase item count _testItemCount++; _serviceStub.doQuery(queryInfo, new Callback<DNSQueryInfo, DNSQueryResponse>() { @Override public void requestComplete(AsyncRequest<DNSQueryInfo, DNSQueryResponse> request) { if (request.getOutput().getStatus() == DNSQueryResponse.Status.SUCCESS) { LOG.info("Request Succeeded for Host:" + hostName + " IPAddress:" + IPAddressUtils.IntegerToIPAddressString(request.getOutput().getAddress()) + " TTL:" + request.getOutput().getTtl() + "(" + (request.getOutput().getTtl() - System.currentTimeMillis()) + ")Source:" + request.getOutput().getSourceServer()); } else { LOG.info("Request Failed for Host:" + hostName + " Reason:" + request.getOutput().getErrorDesc() + " Source:" + request.getOutput().getSourceServer()); } LOG.info("Total:" + _testItemCount + " Complete:" + _itemsComplete.get()); _itemsComplete.incrementAndGet(); // release the semaphore _blockingSempahore.release(); } }); } if (_testItemCount - _itemsComplete.get() > 5000) { LOG.info("Queued Count:" + (_testItemCount - _itemsComplete.get()) + ". Waiting for Queued Count to drop to 1000"); while (_testItemCount - _itemsComplete.get() > 1000) { LOG.info("Waiting for Count to Go Below 1000 (" + (_testItemCount - _itemsComplete.get()) + ")"); try { _blockingSempahore.acquire(); } catch (InterruptedException e) { } } } } LOG.info("Done Processing Test File. Entry Count:" + _testItemCount); JVMStats.dumpMemoryStats(); } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); } finally { try { reader.close(); } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); } } LOG.info("Waiting on all items to complete..."); while (_itemsComplete.get() != _testItemCount) { try { _blockingSempahore.acquire(); } catch (InterruptedException e) { } if (_itemsComplete.get() % 1000 == 0) { LOG.info("Completed Another 1000 Items"); } } LOG.info("All items to completed..."); }
From source file:biospectra.index.Indexer.java
public synchronized void index(File fastaDoc, File taxonDoc) throws Exception { if (fastaDoc == null) { throw new IllegalArgumentException("fastaDoc is null"); }/*ww w. j a v a2 s. c om*/ String taxonTree = ""; if (taxonDoc != null && taxonDoc.exists()) { FileReader reader = new FileReader(taxonDoc); taxonTree = IOUtils.toString(reader); IOUtils.closeQuietly(reader); } FASTAReader reader = FastaFileReader.getFASTAReader(fastaDoc); FASTAEntry read = null; while ((read = reader.readNext()) != null) { String headerLine = read.getHeaderLine(); if (headerLine.startsWith(">")) { headerLine = headerLine.substring(1); } final String f_filename = fastaDoc.getName(); final String sequence = read.getSequence(); final String header = headerLine; final String f_taxonTree = taxonTree; final boolean f_minStrandKmer = this.minStrandKmer; Runnable worker = new Runnable() { @Override public void run() { try { Document doc = freeQueue.poll(); if (doc == null) { doc = new Document(); Field filenameField = new StringField(IndexConstants.FIELD_FILENAME, "", Field.Store.YES); Field headerField = new StringField(IndexConstants.FIELD_HEADER, "", Field.Store.YES); Field sequenceDirectionField = new StringField(IndexConstants.FIELD_SEQUENCE_DIRECTION, "", Field.Store.YES); Field taxonTreeField = new StringField(IndexConstants.FIELD_TAXONOMY_TREE, "", Field.Store.YES); Field sequenceField = new TextField(IndexConstants.FIELD_SEQUENCE, "", Field.Store.NO); doc.add(filenameField); doc.add(headerField); doc.add(sequenceDirectionField); doc.add(taxonTreeField); doc.add(sequenceField); } StringField filenameField = (StringField) doc.getField(IndexConstants.FIELD_FILENAME); StringField headerField = (StringField) doc.getField(IndexConstants.FIELD_HEADER); StringField sequenceDirectionField = (StringField) doc .getField(IndexConstants.FIELD_SEQUENCE_DIRECTION); StringField taxonTreeField = (StringField) doc.getField(IndexConstants.FIELD_TAXONOMY_TREE); TextField sequenceField = (TextField) doc.getField(IndexConstants.FIELD_SEQUENCE); filenameField.setStringValue(f_filename); headerField.setStringValue(header); taxonTreeField.setStringValue(f_taxonTree); if (f_minStrandKmer) { // min-strand sequenceDirectionField.setStringValue("min_strand"); sequenceField.setStringValue(sequence); indexWriter.addDocument(doc); } else { // forward-strand sequenceDirectionField.setStringValue("forward"); sequenceField.setStringValue(sequence); indexWriter.addDocument(doc); // reverse-strand sequenceDirectionField.setStringValue("reverse"); sequenceField.setStringValue(SequenceHelper.getReverseComplement(sequence)); indexWriter.addDocument(doc); } freeQueue.offer(doc); } catch (Exception ex) { LOG.error("Exception occurred during index construction", ex); } } }; this.executor.execute(worker); } reader.close(); }
From source file:org.kuali.kfs.module.ld.batch.service.impl.LaborPosterServiceImpl.java
/** * post the qualified origin entries into Labor Ledger tables * /*from w w w . j a v a 2 s . co m*/ * @param validGroup the origin entry group that holds the valid transactions * @param invalidGroup the origin entry group that holds the invalid transactions * @param runDate the data when the process is running */ protected void postLaborLedgerEntries(Date runDate) { LOG.debug("postLaborLedgerEntries() started.........................."); numberOfErrorOriginEntry = 0; // change file name to FIS String postInputFileName = batchFileDirectoryName + File.separator + LaborConstants.BatchFileSystem.POSTER_INPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION; String postErrFileName = batchFileDirectoryName + File.separator + LaborConstants.BatchFileSystem.POSTER_ERROR_OUTPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION; FileReader INPUT_GLE_FILE = null; try { INPUT_GLE_FILE = new FileReader(postInputFileName); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { POSTER_OUTPUT_ERR_FILE_ps = new PrintStream(postErrFileName); } catch (IOException e) { LOG.error("postLaborLedgerEntries cannot open file: " + e.getMessage(), e); throw new RuntimeException(e); } int lineNumber = 0; int loadedCount = 0; int numberOfSelectedOriginEntry = 0; LaborLedgerUnitOfWork laborLedgerUnitOfWork = new LaborLedgerUnitOfWork(); LedgerSummaryReport ledgerSummaryReport = new LedgerSummaryReport(); Map<String, Integer> reportSummary = this.constructPosterReportSummary(); Map<String, Integer> glEntryReportSummary = this.constructGlEntryReportSummary(); try { BufferedReader INPUT_GLE_FILE_br = new BufferedReader(INPUT_GLE_FILE); String currentLine = INPUT_GLE_FILE_br.readLine(); while (currentLine != null) { LaborOriginEntry laborOriginEntry = null; try { lineNumber++; if (!StringUtils.isEmpty(currentLine) && !StringUtils.isBlank(currentLine.trim())) { laborOriginEntry = new LaborOriginEntry(); // checking parsing process and stop poster when it has errors. List<Message> parsingError = new ArrayList<Message>(); parsingError = laborOriginEntry.setFromTextFileForBatch(currentLine, lineNumber); if (parsingError.size() > 0) { throw new RuntimeException("Exception happened from parsing process"); } loadedCount++; if (loadedCount % 1000 == 0) { LOG.info(loadedCount + " " + laborOriginEntry.toString()); } boolean isPostable = this.postSingleEntryIntoLaborLedger(laborOriginEntry, reportSummary, runDate, currentLine); if (isPostable) { this.updateReportSummary(glEntryReportSummary, ORIGN_ENTRY, KFSConstants.OperationType.READ); this.writeLaborGLEntry(laborOriginEntry, laborLedgerUnitOfWork, runDate, lineNumber, glEntryReportSummary); ledgerSummaryReport.summarizeEntry(laborOriginEntry); numberOfSelectedOriginEntry++; laborOriginEntry = null; } } currentLine = INPUT_GLE_FILE_br.readLine(); } catch (RuntimeException re) { // catch here again, it should be from postSingleEntryIntoLaborLedger LOG.error("postLaborLedgerEntries stopped due to: " + re.getMessage() + " on line number : " + loadedCount, re); LOG.error("laborOriginEntry failure occured on: " + laborOriginEntry == null ? null : laborOriginEntry.toString()); throw new RuntimeException( "Unable to execute: " + re.getMessage() + " on line number : " + loadedCount, re); } } this.writeLaborGLEntry(null, laborLedgerUnitOfWork, runDate, lineNumber, glEntryReportSummary); INPUT_GLE_FILE_br.close(); INPUT_GLE_FILE.close(); POSTER_OUTPUT_ERR_FILE_ps.close(); this.fillPosterReportWriter(lineNumber, reportSummary, glEntryReportSummary); this.fillGlEntryReportWriter(glEntryReportSummary); // Generate Error Listing Report ledgerSummaryReport.writeReport(ledgerSummaryReportWriterService); new TransactionListingReport().generateReport(errorListingReportWriterService, new LaborOriginEntryFileIterator(new File(postErrFileName))); } catch (IOException ioe) { LOG.error("postLaborLedgerEntries stopped due to: " + ioe.getMessage(), ioe); throw new RuntimeException( "Unable to execute: " + ioe.getMessage() + " on line number : " + loadedCount, ioe); } }
From source file:edu.jhu.cvrg.services.nodeDataService.DataStaging.java
private HSSFSheet consolidateAlgorithmFiles(int algorithmCode, HSSFSheet sheet, String subjectIds, String userId, String fileNames, boolean isPublic, ApacheCommonsFtpWrapper ftpClient) { boolean firstToken = true; StringTokenizer tokenizer = new StringTokenizer(subjectIds, "^"); StringTokenizer fileTokenizer = new StringTokenizer(fileNames, "^"); String currentSubject = null; int lineNumber = 0; String headerIndicator = null; switch (algorithmCode) { case 0://from w w w . j a v a2s. co m headerIndicator = CHESNOKOV_HEADER_INDICATOR; break; case 1: headerIndicator = BERGER_HEADER_INDICATOR; break; } String directory = localFtpRoot + sep + userId + utils.generateTimeStamp(); while (tokenizer.hasMoreTokens() && fileTokenizer.hasMoreTokens()) { currentSubject = tokenizer.nextToken(); System.out.println(currentSubject); String file = fileTokenizer.nextToken(); String bareFile = file.substring(file.lastIndexOf("/") + 1); try { ftpClient.downloadFile(file, directory + bareFile); FileReader fi = new FileReader(directory + bareFile); BufferedReader br = new BufferedReader(fi); String thisLine = null, value = null; int inputLineNumber = 0; while ((thisLine = br.readLine()) != null) { boolean isHeader = false; isHeader = thisLine.contains(headerIndicator); if (thisLine != null && thisLine.length() > 0 && (firstToken || !isHeader)) { HSSFRow rowOut = sheet.createRow(lineNumber); StringTokenizer rowTokenizer = new StringTokenizer(thisLine, ","); HSSFCell cellOut; int colNumber = 0; while (rowTokenizer.hasMoreTokens()) { cellOut = rowOut.createCell(colNumber); String replacePipes = rowTokenizer.nextToken(); if (isHeader) { replacePipes = replacePipes.replaceAll("\\|", ","); value = replacePipes; StringTokenizer temp = new StringTokenizer(replacePipes, ","); if (temp.countTokens() > 1) { HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL); link.setAddress(temp.nextToken()); cellOut.setHyperlink(link); value = temp.nextToken().trim(); } cellOut.setCellValue(value); sheet.setColumnWidth(colNumber, (value.length() + 3) * 256); } else { cellOut.setCellValue(replacePipes); if (sheet.getColumnWidth(colNumber) / 256 < replacePipes.length()) sheet.setColumnWidth(colNumber, replacePipes.length() * 256); } colNumber++; } lineNumber++; } inputLineNumber++; } fi.close(); br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //} firstToken = false; } return sheet; }
From source file:com.example.sensingapp.SensingApp.java
private void readUnUploadedFileName() { String sUnUploadedFileNameFilePath = ""; File flFile;//from w ww.j a va 2s.c o m FileReader fr; BufferedReader br; String sLine = ""; m_lstUnUploadedFileName.clear(); sUnUploadedFileNameFilePath = m_sSettingFoler + File.separator + m_sUnUploadedFileName; flFile = new File(sUnUploadedFileNameFilePath); if (flFile.exists()) { //Derive existing labels try { fr = new FileReader(sUnUploadedFileNameFilePath); br = new BufferedReader(fr); while ((sLine = br.readLine()) != null) { m_lstUnUploadedFileName.add(sLine); } fr.close(); } catch (Exception e) { } } }
From source file:it.geosolutions.geobatch.task.TaskExecutor.java
private String setScriptArguments(final String defaultScriptPath, final String inputFilePath, String outputName, final File outXmlFile) throws IOException { String destFilePath = null;/*ww w .j av a 2 s.co m*/ boolean overwriteOutput = false; if (outputName != null && outputName.trim().length() > 0) { overwriteOutput = true; if (outputName.startsWith("*.")) { final String outputExt = outputName.substring(2, outputName.length()); destFilePath = new StringBuilder(FilenameUtils.getFullPath(inputFilePath)).append(File.separator) .append(FilenameUtils.getBaseName(inputFilePath)).append(".").append(outputExt).toString(); } else { destFilePath = new StringBuilder(FilenameUtils.getFullPath(inputFilePath)).append(File.separator) .append(FilenameUtils.getBaseName(inputFilePath)).append(".").append(outputName).toString(); } } // Create FileReader Object FileReader inputFileReader = new FileReader(defaultScriptPath); FileWriter outputFileWriter = new FileWriter(outXmlFile); try { // Create Buffered/PrintWriter Objects BufferedReader inputStream = new BufferedReader(inputFileReader); PrintWriter outputStream = new PrintWriter(outputFileWriter); String inLine = null; boolean sourcePresent = false; boolean destinationPresent = false; while ((inLine = inputStream.readLine()) != null) { // Handle KeyWords if (inLine.trim().startsWith(SOURCE_TAG_OPEN)) { if (inLine.trim().endsWith(SOURCE_TAG_CLOSE)) { // source file specified on the same line inLine = new StringBuilder(SOURCE_TAG_OPEN).append(inputFilePath).append(SOURCE_TAG_CLOSE) .toString(); } else { while ((inLine = inputStream.readLine()) != null) { if (inLine.trim().endsWith(SOURCE_TAG_CLOSE)) { // source file specified on different lines inLine = new StringBuilder(SOURCE_TAG_OPEN).append(inputFilePath) .append(SOURCE_TAG_CLOSE).toString(); } } } sourcePresent = true; } if (inLine.trim().startsWith(DESTINATION_TAG_OPEN)) { if (inLine.trim().endsWith(DESTINATION_TAG_CLOSE)) { // source file specified on the same line if (overwriteOutput) { inLine = new StringBuilder(DESTINATION_TAG_OPEN).append(destFilePath) .append(DESTINATION_TAG_CLOSE).toString(); } else { final int start = inLine.indexOf(DESTINATION_TAG_OPEN); final int end = inLine.indexOf(DESTINATION_TAG_CLOSE, start + 1); destFilePath = inLine.substring(start + DESTINATION_TAG_OPEN.length(), end); } } else { while ((inLine = inputStream.readLine()) != null) { if (overwriteOutput) { if (inLine.trim().endsWith(DESTINATION_TAG_CLOSE)) { // source file specified on different lines inLine = new StringBuilder(DESTINATION_TAG_OPEN).append(destFilePath) .append(DESTINATION_TAG_CLOSE).toString(); } } else { String newLine = inLine.trim(); if (newLine.trim().endsWith(DESTINATION_TAG_CLOSE)) { // source file specified on different lines if (!newLine.trim().startsWith(DESTINATION_TAG_CLOSE)) { destFilePath = newLine.substring(0, newLine.indexOf(DESTINATION_TAG_CLOSE)); } } else { if (newLine.length() > 0) { destFilePath = newLine; } } } } } destinationPresent = true; } outputStream.println(inLine); } if (sourcePresent && !destinationPresent) { destFilePath = inputFilePath; } } catch (IOException e) { } finally { try { inputFileReader.close(); } catch (IOException e) { } try { outputFileWriter.close(); } catch (IOException e) { } } return destFilePath; }
From source file:com.photon.phresco.framework.rest.api.BuildInfoService.java
@GET @Path("/checkstatus") @Produces(MediaType.APPLICATION_JSON)//w ww .ja va2s . c o m public Response checkStatus(@QueryParam(REST_QUERY_APPDIR_NAME) String appDirName, @QueryParam(REST_QUERY_MODULE_NAME) String module) { ResponseInfo<Boolean> responseData = new ResponseInfo<Boolean>(); String host = null, protocol = null, environmentName = null, port = null; Boolean connectionAlive = false; FileReader readers = null; boolean checkForFailureInLog = false; try { String rootModulePath = ""; String subModuleName = ""; if (StringUtils.isNotEmpty(module)) { rootModulePath = Utility.getProjectHome() + appDirName; subModuleName = module; } else { rootModulePath = Utility.getProjectHome() + appDirName; } String dotPhrescoFolderPath = Utility.getDotPhrescoFolderPath(rootModulePath, subModuleName); File pomFileLocation = Utility.getPomFileLocation(rootModulePath, subModuleName); File configurationInfo = new File(dotPhrescoFolderPath + File.separator + PHRESCO_ENV_CONFIG_FILE_NAME); File runAgainsSourceInfo = new File(dotPhrescoFolderPath + File.separator + RUNAGNSRC_INFO_FILE); File logFile = new File(pomFileLocation.getParent() + File.separator + DO_NOT_CHECKIN_DIR + File.separator + LOG_DIR + File.separator + RUN_AGS_LOG_FILE); if (!runAgainsSourceInfo.exists()) { ResponseInfo<Boolean> finalOutput = responseDataEvaluation(responseData, null, connectionAlive, RESPONSE_STATUS_SUCCESS, PHR710005); return Response.status(Response.Status.OK).entity(finalOutput) .header("Access-Control-Allow-Origin", "*").build(); } checkForFailureInLog = checkForFailureInLog(logFile); if (checkForFailureInLog) { ResponseInfo<Boolean> finalOutput = responseDataEvaluation(responseData, null, connectionAlive, RESPONSE_STATUS_SUCCESS, PHR710005); return Response.status(Response.Status.OK).entity(finalOutput) .header("Access-Control-Allow-Origin", "*").build(); } readers = new FileReader(runAgainsSourceInfo); JSONObject jsonobject = new JSONObject(); JSONParser parser = new JSONParser(); jsonobject = (JSONObject) parser.parse(readers); environmentName = (String) jsonobject.get(SESSION_ENV_NAME); ConfigurationReader reader = new ConfigurationReader(configurationInfo); List<Configuration> config = reader.getConfigurations(environmentName, FrameworkConstants.SERVER); for (Configuration configs : config) { Properties properties = configs.getProperties(); host = properties.getProperty(SERVER_HOST); port = properties.getProperty(SERVER_PORT); protocol = properties.getProperty(PROTOCOL); } connectionAlive = isConnectionAlive(protocol, host, Integer.parseInt(port)); if (connectionAlive) { ResponseInfo<Boolean> finalOutput = responseDataEvaluation(responseData, null, connectionAlive, RESPONSE_STATUS_SUCCESS, PHR700003); return Response.status(Response.Status.OK).entity(finalOutput) .header("Access-Control-Allow-Origin", "*").build(); } else { ResponseInfo<Boolean> finalOutput = responseDataEvaluation(responseData, null, connectionAlive, RESPONSE_STATUS_SUCCESS, PHR710006); return Response.status(Response.Status.OK).entity(finalOutput) .header("Access-Control-Allow-Origin", "*").build(); } } catch (Exception e) { ResponseInfo<Boolean> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR, PHR710007); return Response.status(Response.Status.OK).entity(finalOutput) .header("Access-Control-Allow-Origin", "*").build(); } finally { try { if (readers != null) { readers.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:skoa.helpers.Graficos.java
/** * FUNCIN ESTADSTICA PARA HALLAR LA EVOLUCIN DE DIFERENCIAS. * PORCENTAJE=(v1-v2)/v1*100/* w w w.j a va 2 s . com*/ * DIFERENCIA=(v1-v2) * En caso de que no se encuentren los dos valores, y slo haya 1 o ninguno, se obvia esa medicion. * Vamos a comparar segn un intervalo en minutos. Si en ese intervalo, hay + de 1 medicion, se hace la media. * @param i, subopcion: 1=porcentaje y otro=diferencia normal */ private void aplicarFormula(int i) { Vector<String> nombresFicheros2 = new Vector<String>(nombresFicheros); //Copiamos los nombres String freferencia = nombresFicheros2.get(0); //Se coge el 1 fichero de referencia, al que se le irn aadiendo los datos. nombresFicheros2.remove(0); String fcomparar = nombresFicheros2.get(0); compararFicheros(freferencia, fcomparar); //Nombre del fichero resultante: n=tipo-intervalo-x-xx-xx-y-yy-yy String d1, d2, n; n = freferencia.substring(0, 4); //Hasta el segundo '-', es decir coge el tipo de consulta e intervalo //d1=freferencia.substring(freferencia.length()-10, freferencia.length()-4); //La DG del fich referencia (1 columna de valores) //d2=fcomparar.substring(fcomparar.length()-10, fcomparar.length()-4); //La DG del otro fichero (2 columna de valores) d1 = freferencia.substring(freferencia.indexOf(" ") - 6, freferencia.indexOf(" ")); d2 = fcomparar.substring(fcomparar.indexOf(" ") - 6, fcomparar.indexOf(" ")); //System.out.println(d1+"-"+d2+"."); n = n + "-" + d1 + "-" + d2; //Fichero usado para obtener la serie. Es el fichero resultante de aplicarFormulaP() FileReader fr = null; BufferedReader linea = null; String line; //Leemos el fichero unificado.txt con los dos valores y les aplicamos la frmula (V1/V2)*100 File uni = new File(ruta + "unificado.txt"); try { int i1 = 1; fr = new FileReader(uni); linea = new BufferedReader(fr); unidad = ""; while ((line = linea.readLine()) != null) { //Lectura del fichero String v, f, l; float v1 = 0, v2; f = line.substring(0, line.indexOf("\t")); l = line.substring(line.indexOf("\t") + 1); //l tiene hasta los valores. if (l.indexOf("0") == 0) v1 = 0; //El primer valor es un 0. else if (l.indexOf(" ") > 0) { //El 1 valor es distinto de 0, por lo convertimos a int. v = l.substring(0, l.indexOf(" ")); v1 = Float.parseFloat(v); if (i1 == 1) { String aux = l.substring(l.indexOf(" ") + 1); if (aux.indexOf("\t") >= 0) aux = aux.substring(0, aux.indexOf("\t")); unidad = unidad + aux; //i1=0; } } if (l.indexOf("\t") >= 0) { //Si encontramos \t, quiere decir que hay un segundo valor !=0 l = l.substring(l.indexOf("\t") + 1); v = l.substring(0, l.indexOf(" ")); v2 = Float.parseFloat(v); /*if (i1==1){ //unidad=unidad+l.substring(l.indexOf(" ")+1); i1=0; }*/ } else v2 = 0; //Una vez tenemos los valores en v1 y v2, aplicamos la formula. Si el numerador y/o denominador es 0 //entonces el resultado ser directamente 0. En v1, guardamos el resultado (reusamos esta variable) if (v1 == 0 || v2 == 0) v1 = 0; else if (v1 == 0 && v2 == 0) v1 = 0; else { if (i == 1) { //HALLA EL PORCENTAJE. float r = v1 - v2; if (r < 0) r = 0 - r; v1 = (r / v1) * 100; } else v1 = v1 - v2; //HALLA EL VALOR de la diferencia, que puede ser negativo. } guardar(f, v1, n); i1 = 0; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) fr.close(); //Se cierra si todo va bien. } catch (Exception e2) { //Sino salta una excepcion. e2.printStackTrace(); } } if (i == 1) unidad = "%" + "\t" + unidad; else unidad = "ABS" + "\t" + unidad; }
From source file:skoa.helpers.Graficos.java
private DefaultCategoryDataset obtenerSerieBarras2(Vector<String> v) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); File archivo = new File(ruta + "estadisticas.txt"); FileReader fr = null; BufferedReader linea = null;/* w w w . j a v a2s . c o m*/ String line; try { fr = new FileReader(archivo); linea = new BufferedReader(fr); //Se crea para leer las lineas int d = 0, m = 0, a = 0, a1 = 0, m1 = 0, d1 = 0, j; String aux; while ((line = linea.readLine()) != null) { //Lectura del fichero int i = line.indexOf("\t"); String f = line.substring(0, i); String valor = line.substring(i + 1); //Obtencion del dia, mes y ao de la fecha. j = f.indexOf("-"); aux = f.substring(0, j); a = Integer.parseInt(aux); f = f.substring(j + 1); j = f.indexOf("-"); aux = f.substring(0, j); m = Integer.parseInt(aux); f = f.substring(j + 1); j = f.indexOf(" "); aux = f.substring(0, j); d = Integer.parseInt(aux); //Obtencion de la hora de la fecha. f = f.substring(j + 1); if (fechaInicial.contentEquals("")) fechaInicial = d + "/" + m + "/" + a + " " + f; //Variable para la grfica fechaFinal = d + "/" + m + "/" + a + " " + f; j = f.indexOf(":"); if (a1 == 0 & m1 == 0 & d1 == 0) { //Inicializacin: Primera fecha. a1 = a; m1 = m; d1 = d; } else { if (a1 != a) { a1 = a; if (m1 != m) m1 = m; if (d1 != d) d1 = d; } else if (m1 != m) { m1 = m; if (d1 != d) d1 = d; } else if (d1 != d) d1 = d; } String sv = ""; String fecha = "" + d1 + "-" + m1 + " " + f; Double ev; for (int l = 0; l < 3; l++) { //Hasta 3, porque en cada linea hay 3 valores: max,min y med. int p1 = valor.indexOf("\t"); if (p1 != (-1)) { sv = valor.substring(0, p1); valor = valor.substring(p1 + 1); } else { //Ultimo valor. sv = valor; valor = ""; } ev = Double.parseDouble(sv); //Valor a guardar dataset.setValue(ev, nombresDGs.elementAt(l), fecha); } } //fin while leer lineas } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) fr.close(); //Se cierra si todo va bien. } catch (Exception e2) { //Sino salta una excepcion. e2.printStackTrace(); } } return dataset; }
From source file:skoa.helpers.Graficos.java
private DefaultCategoryDataset obtenerSerieBarras(Vector<String> v) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); File archivo = new File(ruta + "diferenciaAplicada.txt"); FileReader fr = null; BufferedReader linea = null;// w w w .ja v a 2s .co m String line; try { fr = new FileReader(archivo); linea = new BufferedReader(fr); //Se crea para leer las lineas int d = 0, m = 0, a = 0, a1 = 0, m1 = 0, d1 = 0, j; String aux; while ((line = linea.readLine()) != null) { //Lectura del fichero int i = line.indexOf("\t"); String f = line.substring(0, i); String valor = line.substring(i + 1); //Obtencion del dia, mes y ao de la fecha. j = f.indexOf("-"); aux = f.substring(0, j); a = Integer.parseInt(aux); f = f.substring(j + 1); j = f.indexOf("-"); aux = f.substring(0, j); m = Integer.parseInt(aux); f = f.substring(j + 1); j = f.indexOf(" "); aux = f.substring(0, j); d = Integer.parseInt(aux); //Obtencion de la hora de la fecha. f = f.substring(j + 1); if (fechaInicial.contentEquals("")) fechaInicial = d + "/" + m + "/" + a + " " + f; //Variable para la grfica fechaFinal = d + "/" + m + "/" + a + " " + f; j = f.indexOf(":"); if (a1 == 0 & m1 == 0 & d1 == 0) { //Inicializacin: Primera fecha. a1 = a; m1 = m; d1 = d; } else { if (a1 != a) { a1 = a; if (m1 != m) m1 = m; if (d1 != d) d1 = d; } else if (m1 != m) { m1 = m; if (d1 != d) d1 = d; } else if (d1 != d) d1 = d; } String sa = "", sv = ""; String fecha = "" + d1 + "-" + m1 + " " + f; Double ev; for (int l = 0; l < v.size(); l++) { int p1 = valor.indexOf("\t"); if (p1 != (-1)) { sa = valor.substring(0, p1); valor = valor.substring(p1 + 1); } else { //Ultimo valor. sa = valor; valor = ""; } int pu = sa.indexOf(" "); sv = sa.substring(0, pu - 1); ev = Double.parseDouble(sv); //Valor a guardar dataset.setValue(ev, nombresDGs.elementAt(l), fecha); } } //fin while leer lineas } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) fr.close(); //Se cierra si todo va bien. } catch (Exception e2) { //Sino salta una excepcion. e2.printStackTrace(); } } return dataset; }