List of usage examples for java.io FileReader close
public void close() throws IOException
From source file:GestoSAT.GestoSAT.java
public GestoSAT() { File f = new File("confGestoSAT"); if (f.exists()) { FileReader file; try {/*from w w w . ja va 2 s. co m*/ file = new FileReader("confGestoSAT"); BufferedReader b = new BufferedReader(file); String cadena; cadena = b.readLine(); String[] valores = cadena.split(";"); mySQL.add(valores[0]); mySQL.add(Math.abs(Integer.parseInt(valores[1])) + ""); mySQL.add(valores[2]); mySQL.add(valores[3]); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3)); confSeg.add(valores[4]); confSeg.add(Math.abs(Integer.parseInt(valores[5])) + ""); confSeg.add(valores[6]); confSeg.add(valores[7]); iva = Math.abs(Integer.parseInt(valores[8])); file.close(); } catch (FileNotFoundException ex) { Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.MafFileProcessor.java
@Override protected File doWork(final File mafFile, final QcContext context) throws ProcessorException { // make sure the disease is set if (context.getArchive() != null) { DiseaseContextHolder.setDisease(context.getArchive().getTumorType()); }/* w ww . j a va 2s . c om*/ FileReader fileReader = null; BufferedReader bufferedReader = null; try { // open file fileReader = new FileReader(mafFile); bufferedReader = new BufferedReader(fileReader); int lineNum = 0; // find first non-blank line not starting with #, this is the header String headerLine = bufferedReader.readLine(); lineNum++; while (StringUtils.isEmpty(headerLine.trim()) || StringUtils.startsWith(headerLine, COMMENT_LINE_TOKEN)) { headerLine = bufferedReader.readLine(); lineNum++; } final List<String> headers = Arrays.asList(headerLine.split("\\t")); context.setFile(mafFile); final Map<String, Integer> fieldOrder = mapFieldOrder(headers); // need to find out the file id for this maf file final Long mafFileId = fileInfoQueries.getFileId(mafFile.getName(), context.getArchive().getId()); if (mafFileId == null || mafFileId == -1) { context.getArchive().setDeployStatus(Archive.STATUS_IN_REVIEW); throw new ProcessorException(new StringBuilder().append("File '").append(mafFile.getName()) .append("' was not found in the database").toString()); } if (isAddMafInfo(mafFileId)) { HashMap<String, BCRID> biospecimens = new HashMap<String, BCRID>(); String line; while ((line = bufferedReader.readLine()) != null) { lineNum++; if (!StringUtils.isBlank(line.trim()) && !StringUtils.startsWith(line, COMMENT_LINE_TOKEN)) { final String[] row = line.split("\\t"); try { processRow(row, fieldOrder, mafFileId, biospecimens, context, mafFile, lineNum); // If exceeds batch size store it in the database if (biospecimens.size() >= getBatchSize()) { try { insertBiospecimenToFileRelationships(biospecimens, context, mafFile); } catch (UUIDException ue) { throw new ProcessorException(ue.getMessage(), ue); } biospecimens.clear(); } } catch (DataAccessException e) { // catch DB errors per line context.getArchive().setDeployStatus(Archive.STATUS_IN_REVIEW); context.addError(MessageFormat.format(MessagePropertyType.MAF_FILE_PROCESSING_ERROR, mafFile.getName(), new StringBuilder().append("Mutation information from file at line '") .append(lineNum).append("' was not successfully added. Root cause: ") .append(e.getMessage()).toString())); } } } // process remaining biospecimens if (biospecimens.size() > 0) { try { insertBiospecimenToFileRelationships(biospecimens, context, mafFile); } catch (UUIDException ue) { context.getArchive().setDeployStatus(Archive.STATUS_IN_REVIEW); throw new ProcessorException(ue.getMessage(), ue); } catch (DataAccessException e) { context.getArchive().setDeployStatus(Archive.STATUS_IN_REVIEW); throw new ProcessorException(e.getMessage(), e); } biospecimens.clear(); } } } catch (IOException e) { context.getArchive().setDeployStatus(Archive.STATUS_IN_REVIEW); throw new ProcessorException( new StringBuilder().append("Error reading maf file ").append(mafFile.getName()).toString()); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { // ignore } } if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { // ignore } } } return mafFile; }
From source file:com.teamnx.util.CSVToDateBase.java
/** * @param fileName//from ww w.j a v a 2 s . c o m * @param type * @return */ public List readCsvFile(String fileName, int type) { FileReader fileReader = null; CSVParser csvFileParser = null; List list = null; //CSVFormatheader mapping CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(file_header); try { //?FileReader object fileReader = new FileReader(fileName); //? CSVParser object csvFileParser = new CSVParser(fileReader, csvFileFormat); //CSVrecords List<CSVRecord> csvRecords = csvFileParser.getRecords(); // CSV switch (type) { case USER: List<User> userList = new ArrayList<User>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); //? User user = new User(); user.setId(record.get("id")); user.setName(record.get("name")); user.setPassword(record.get("password")); user.setDepartment_id(Integer.parseInt(record.get("department_id"))); user.setCharacter(Integer.parseInt(record.get("character"))); user.setClass_id(record.get("class_id")); user.setDepartment_name(record.get("department_name")); userList.add(user); } list = userList; break; case DEPARTMENT: List<Department> departmentList = new ArrayList<Department>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); //? Department department = new Department(); department.setId(Integer.parseInt(record.get("id"))); department.setName(record.get("name")); departmentList.add(department); } list = departmentList; break; case COURSE: List<Course> courseList = new ArrayList<Course>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); //? Course course = new Course(); course.setId(record.get("id")); course.setName(record.get("name")); course.setDepartment_id(Integer.parseInt(record.get("department_id"))); course.setStart_time(Integer.parseInt(record.get("start_time"))); course.setEnd_time(Integer.parseInt(record.get("end_time"))); course.setPosition(record.get("position")); course.setSchedule(record.get("schedule")); course.setYear(Integer.parseInt(record.get("year"))); course.setSemester(Integer.parseInt(record.get("semester"))); int j = Integer.parseInt(record.get("category")); course.setCategory(j == 1 ? true : false); course.setMax_member(Integer.parseInt(record.get("max_member"))); courseList.add(course); } list = courseList; break; case STUDENT_COURSE: List<StudentCourse> studentCourseList = new ArrayList<StudentCourse>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); StudentCourse studentCourse = new StudentCourse(); studentCourse.setId(record.get("id")); studentCourse.setCourseId(record.get("course_id")); studentCourse.setStudentId(record.get("student_id")); studentCourseList.add(studentCourse); } list = studentCourseList; break; case TEACHER_COURSE: List<TeacherCourse> teacherCourseList = new ArrayList<TeacherCourse>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); TeacherCourse teacherCourse = new TeacherCourse(); teacherCourse.setId(record.get("id")); teacherCourse.setTeacherId(record.get("teacher_id")); teacherCourse.setCourseId(record.get("course_id")); teacherCourseList.add(teacherCourse); } list = teacherCourseList; break; } } catch (Exception e) { e.printStackTrace(); } finally { try { fileReader.close(); csvFileParser.close(); } catch (IOException e) { e.printStackTrace(); } finally { return list; } } }
From source file:skoa.helpers.Graficos.java
private DefaultCategoryDataset obtenerSerieBarrasDual(int col) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); File archivo = new File(ruta + "diferenciaAplicada.txt"); FileReader fr = null; BufferedReader linea = null;//ww w. ja va2 s . 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 a;o 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; if (col == 1) { //Se cogen los valores de la primera columna int p1 = valor.indexOf("\t"); sa = valor.substring(0, p1); int pu = sa.indexOf(" "); sv = sa.substring(0, pu - 1); ev = Double.parseDouble(sv); //Valor a guardar dataset.setValue(ev, nombresDGs.elementAt(0), fecha); dataset.setValue(null, "vacia", fecha); //Le ponemos un nombre cualquiera, xq no se ver } else { //Se cogen los valores de la segunda columna int p1 = valor.indexOf("\t"); sa = valor.substring(p1 + 1); int pu = sa.indexOf(" "); sv = sa.substring(0, pu - 1); ev = Double.parseDouble(sv); //Valor a guardar dataset.setValue(null, "vacia", fecha); dataset.setValue(ev, nombresDGs.elementAt(1), 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:ffx.potential.parsers.XYZFilter.java
/** * {@inheritDoc}/*from w w w . j av a2 s . c o m*/ * * Parse the XYZ File */ @Override public boolean readFile() { File xyzFile = activeMolecularAssembly.getFile(); if (forceField == null) { logger.warning(" No force field is associated with " + xyzFile.toString()); return false; } try { FileReader fr = new FileReader(xyzFile); BufferedReader br = new BufferedReader(fr); String data = br.readLine(); // Read blank lines at the top of the file while (data != null && data.trim().equals("")) { data = br.readLine(); } if (data == null) { return false; } String tokens[] = data.trim().split(" +", 2); int numberOfAtoms = Integer.parseInt(tokens[0]); if (numberOfAtoms < 1) { return false; } if (tokens.length == 2) { getActiveMolecularSystem().setName(tokens[1]); } logger.info("\n Opening " + xyzFile.getName() + " with " + numberOfAtoms + " atoms\n"); // The header line is reasonable - prepare to parse atom lines. Hashtable<Integer, Integer> labelHash = new Hashtable<Integer, Integer>(); int label[] = new int[numberOfAtoms]; int bonds[][] = new int[numberOfAtoms][8]; double d[][] = new double[numberOfAtoms][3]; boolean renumber = false; atomList = new ArrayList<Atom>(); // Loop over the expected number of atoms. for (int i = 0; i < numberOfAtoms; i++) { if (!br.ready()) { return false; } data = br.readLine(); if (data == null) { logger.warning("Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName()); return false; } tokens = data.trim().split(" +"); if (tokens == null || tokens.length < 6) { logger.warning("Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName()); return false; } // Valid number of tokens, so try to parse this line. label[i] = Integer.parseInt(tokens[0]); // Check for valid atom numbering, or flag for re-numbering. if (label[i] != i + 1) { renumber = true; } String atomName = tokens[1]; d[i][0] = Double.parseDouble(tokens[2]); d[i][1] = Double.parseDouble(tokens[3]); d[i][2] = Double.parseDouble(tokens[4]); int type = Integer.parseInt(tokens[5]); AtomType atomType = forceField.getAtomType(Integer.toString(type)); if (atomType == null) { StringBuilder message = new StringBuilder("Check atom type "); message.append(type).append(" for Atom ").append(i + 1); message.append(" in ").append(activeMolecularAssembly.getFile().getName()); logger.warning(message.toString()); return false; } Atom a = new Atom(i + 1, atomName, atomType, d[i]); atomList.add(a); // Bond Data int numberOfBonds = tokens.length - 6; for (int b = 0; b < 8; b++) { if (b < numberOfBonds) { int bond = Integer.parseInt(tokens[6 + b]); bonds[i][b] = bond; } else { bonds[i][b] = 0; } } } // Check if this is an archive. if (br.ready()) { // Read past blank lines between archive files data = br.readLine().trim(); while (data != null && data.equals("")) { data = br.readLine().trim(); } if (data != null) { tokens = data.split(" +", 2); if (tokens != null && tokens.length > 0) { try { int archiveNumberOfAtoms = Integer.parseInt(tokens[0]); if (archiveNumberOfAtoms == numberOfAtoms) { setType(FileType.ARC); } } catch (Exception e) { tokens = null; } } } } br.close(); fr.close(); // Try to renumber if (renumber) { for (int i = 0; i < numberOfAtoms; i++) { if (labelHash.containsKey(label[i])) { logger.warning("Two atoms have the same index: " + label[i]); return false; } labelHash.put(label[i], i + 1); } for (int i = 0; i < numberOfAtoms; i++) { int j = -1; while (j < 3 && bonds[i][++j] > 0) { bonds[i][j] = labelHash.get(bonds[i][j]); } } } bondList = new ArrayList<Bond>(); int c[] = new int[2]; for (int i = 1; i <= numberOfAtoms; i++) { int a1 = i; int j = -1; while (j < 7 && bonds[i - 1][++j] > 0) { int a2 = bonds[i - 1][j]; if (a1 < a2) { if (a1 > numberOfAtoms || a1 < 1 || a2 > numberOfAtoms || a2 < 1) { logger.warning("Check the Bond Bewteen " + a1 + " and " + a2 + " in " + activeMolecularAssembly.getFile().getName()); return false; } // Check for bidirectional connection boolean bidirectional = false; int k = -1; while (k < 7 && bonds[a2 - 1][++k] > 0) { int a3 = bonds[a2 - 1][k]; if (a3 == a1) { bidirectional = true; break; } } if (!bidirectional) { logger.warning("Check the Bond Bewteen " + a1 + " and " + a2 + " in " + activeMolecularAssembly.getFile().getName()); return false; } Atom atom1 = atomList.get(a1 - 1); Atom atom2 = atomList.get(a2 - 1); if (atom1 == null || atom2 == null) { logger.warning("Check the Bond Bewteen " + a1 + " and " + a2 + " in " + activeMolecularAssembly.getFile().getName()); return false; } Bond bond = new Bond(atom1, atom2); c[0] = atom1.getAtomType().atomClass; c[1] = atom2.getAtomType().atomClass; String key = BondType.sortKey(c); BondType bondType = forceField.getBondType(key); if (bondType == null) { logger.severe("No BondType for key: " + key); } else { bond.setBondType(bondType); } bondList.add(bond); } } } /* if (getType() == FileType.ARC) { return readtrajectory(); } */ return true; } catch (IOException e) { logger.severe(e.toString()); } return false; }
From source file:com.diversityarrays.kdxplore.specgroup.SpecimenGroupEditor.java
private List<Specimen> importFile(File file) throws IOException { List<Specimen> specimens = new ArrayList<>(); Map<String, BreedingMethod> methodByLowcaseName = new HashMap<>(); if (offlineData != null) { KddartReferenceData refdata = offlineData.getKddartReferenceData(); if (refdata != null) { for (BreedingMethod bm : refdata.getBreedingMethods()) { methodByLowcaseName.put(bm.getBreedingMethodName().toLowerCase(), bm); }//from w w w . j ava2 s .co m } } SpecimenColumnHelper sch = new SpecimenColumnHelper(); FileReader reader = null; try { reader = new FileReader(file); @SuppressWarnings("resource") CSVReader csvReader = new CSVReader(reader); String[] lineFields; Map<Integer, Column> columnByInputIndex = null; int lineNumber = 0; while (null != (lineFields = csvReader.readNext())) { if (!Check.isEmpty(lineFields[0])) { ++lineNumber; // Line1 Column1 == "SpecimenName" // else we only do the first column as the specimen name if (lineNumber == 1) { if (lineFields[0].equals(sch.specimenNameColumn.name())) { columnByInputIndex = new HashMap<>(); // Heading row columnByInputIndex.put(0, sch.specimenNameColumn); for (int inputIndex = 1; inputIndex < lineFields.length; ++inputIndex) { String heading = lineFields[inputIndex]; for (Column c : sch.columns) { if (c.name().equals(heading)) { columnByInputIndex.put(inputIndex, c); break; } } } // Skip to next line continue; } } Specimen s = new Specimen(); if (columnByInputIndex == null) { s.setSpecimenName(lineFields[0]); } else { for (int index = lineFields.length; --index >= 0;) { String columnValue = lineFields[index]; Column c = columnByInputIndex.get(index); if (c != null) { Field fld = sch.fieldByColumn.get(c); if (fld != null) { if (sch.breedingMethodIdColumn == c) { BreedingMethod bm = methodByLowcaseName.get(columnValue); if (bm != null) { s.setExtraData(BREEDING_METHOD_NAME, bm.getBreedingMethodName()); s.setBreedingMethodId(bm.getBreedingMethodId()); } else { s.setExtraData(BREEDING_METHOD_NAME, columnValue); } } else { Object value = null; if (Integer.class == fld.getType()) { if (!Check.isEmpty(columnValue)) { try { Integer i = Integer.valueOf(columnValue); value = i; } catch (NumberFormatException ignore) { } } } else if (String.class == fld.getType()) { value = columnValue; } if (value != null) { try { fld.set(s, value); } catch (IllegalArgumentException | IllegalAccessException ignore) { } } } } } } } specimens.add(s); } } return specimens; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } } }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.MafFileValidator.java
/** * Validates a maf file. Will add errors found. * * @param mafFile the file to validate/*from w w w .j a v a 2s .c om*/ * @param context the qc context * @return whether validation passed or not * @throws IOException if the file could not be opened/read * @throws gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.Processor.ProcessorException * if an error happens */ protected boolean validate(final File mafFile, final QcContext context) throws IOException, ProcessorException { FileReader fileReader = null; BufferedReader bufferedReader = null; try { // initialize threadlocal initThreadLocals(); boolean ok = true; context.setFile(mafFile); // set sampleTypes for (SampleType sample : sampleTypeQueries.getAllSampleTypes()) { sampleCodes.put(sample.getSampleTypeCode(), sample.getIsTumor()); } // open file fileReader = new FileReader(mafFile); bufferedReader = new BufferedReader(fileReader); int lineNum = 0; // find first non-blank line not starting with #, this is the header String headerLine = bufferedReader.readLine(); lineNum++; while (StringUtils.isEmpty(headerLine.trim()) || StringUtils.startsWith(headerLine, COMMENT_LINE_TOKEN)) { headerLine = bufferedReader.readLine(); lineNum++; } final List<String> headers = Arrays.asList(headerLine.split("\\t")); // get order of fields from header final Map<String, Integer> fieldOrder = mapFieldOrder(headers); // make sure the field order is correct for (int i = 0; i < getMafFieldList().size(); i++) { if (fieldOrder.get(getMafFieldList().get(i)) == null) { context.addError(MessageFormat.format(MessagePropertyType.MISSING_REQUIRED_COLUMN_ERROR, getMafFieldList().get(i))); // if a column is missing, just return false now return false; } else if (fieldOrder.get(getMafFieldList().get(i)) != i) { context.addError( MessageFormat.format(MessagePropertyType.MAF_FILE_PROCESSING_ERROR, mafFile.getName(), new StringBuilder().append("Expected column '").append(getMafFieldList().get(i)) .append("' to be at index '").append((i + 1)).append("' but found at '") .append((fieldOrder.get(getMafFieldList().get(i)) + 1)).append("'") .toString())); // if order is wrong, make error but ok to continue rest of checks ok = false; } } String line; int initialErrorCount = context.getErrorCount(); while ((line = bufferedReader.readLine()) != null) { lineNum++; if (!StringUtils.isBlank(line.trim()) && !StringUtils.startsWith(line, COMMENT_LINE_TOKEN)) { final String[] row = line.split("\\t"); if (row.length >= fieldOrder.size()) { boolean rowOk = validateRow(row, fieldOrder, lineNum, context, mafFile.getName()); ok = ok && rowOk; } else { context.addError(MessageFormat.format(MessagePropertyType.MAF_FILE_VALIDATION_ERROR, mafFile.getName(), lineNum, new StringBuilder().append("Improper format: expected '").append(fieldOrder.size()) .append("' fields but found '").append(row.length).append("'").toString())); ok = false; } } if (context.getErrorCount() - initialErrorCount > 100) { context.addError("More than 100 errors found, halting MAF validation"); break; } } // validate remaining ids (barcodes or UUIDs) if (context.isStandaloneValidator()) { ok = batchValidate(null, context, mafFile.getName(), true, true); } if (!ok) { context.getArchive().setDeployStatus(Archive.STATUS_INVALID); } return ok; } finally { cleanupThreadLocals(); if (bufferedReader != null) { bufferedReader.close(); } if (fileReader != null) { fileReader.close(); } } }
From source file:skoa.helpers.Graficos.java
private void crearEstadisticas() { SimpleDateFormat formatoDelTexto = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //Sacamos el rango del nombre del fichero. nombreFichero = nombresFicheros.get(0); //En esta consulta slo manejamos 1 fichero. int i = nombreFichero.indexOf("h"); int j = i;/*from w ww . j av a 2s . c om*/ while (true) { if (nombreFichero.charAt(j) != '-') j--; else break; } String rango = nombreFichero.substring(j + 1, i); //Leemos el fichero. Primero cojo la primera lnea que aparezca, saco la fecha y calculo la siguiente fecha //fechaF=fechaI+rango. Y comienzo a trabajar las lineas que se encuentren dentro de este rango. //Despus fechaI=fechaF, y se volver a calcular fechaF. File archivo = new File(ruta + nombreFichero); FileReader fr = null; BufferedReader linea = null; String line; try { fr = new FileReader(archivo); linea = new BufferedReader(fr); line = linea.readLine(); //Leemos la primera lnea para sacar la fecha Inicial. //Si se trata de una DG con valores booleanos, no se hace nada y se genera una grfica VACIA if (posiblesBooleanos(line, 0) || posiblesBooleanos(line, 1)) { //Se crea un archivo vaco. String fil = ruta + "estadisticas.txt"; //PARA USARSE CON LOAD DATA INFILE EN LA BD File fichero_buscado = new File(fil); try { fichero_buscado.createNewFile(); //CREAR FICHERO BufferedWriter bw = new BufferedWriter(new FileWriter(fil, true)); //GUARDAR DATOS bw.write(""); bw.close(); //Cerrar fichero } catch (IOException ioe) { ioe.printStackTrace(); } return; //Se sale del procedimiento } String fechaI = ""; int j1 = line.indexOf("\t"); fechaI = line.substring(0, j1); Date fI = null; fI = formatoDelTexto.parse(fechaI); //FECHA INICIAL Calendar c2 = Calendar.getInstance(); //Debemos hacer uso de una variable calendar para modificar c2.setTime(fI); //las fechas segn el rango pasado. int r = Integer.parseInt(rango); c2.add(Calendar.HOUR_OF_DAY, r); //Incrementamos el n1 de horas segn el rango.Hour_of_day es la hora en formato 24h Date fF = c2.getTime(); //FECHAFINAL=FECHAINICIAL+RANGO. //Inicializacion de las variables usadas en las estadsticas, con los valores de la lnea leida. String aux = line.substring(line.indexOf("\t") + 1); unidad = aux.substring(0, aux.indexOf(" ")); max = min = sum = Float.parseFloat(unidad); aux = aux.substring(aux.indexOf(" ") + 1); unidad = aux; num = 1; while ((line = linea.readLine()) != null) { //Lectura del fichero //Calculamos la siguiente fecha a comparar con la del final del rango. j1 = line.indexOf("\t"); fechaI = line.substring(0, j1); fI = formatoDelTexto.parse(fechaI); if (estadisticas(fI, fF, line.substring(line.indexOf("\t") + 1))) { //Si es true, quiere decir que tenemos que volver a calcular fF. guardarEstadisticas(fechaI); //Calculamos la nueva fecha inicial, que ser la fecha de la line en la que estamos ahora, //que es la siguiente a la fecha final anterior. j1 = line.indexOf("\t"); fechaI = line.substring(0, j1); fI = formatoDelTexto.parse(fechaI); c2.setTime(fI); c2.add(Calendar.HOUR_OF_DAY, r); //Incrementamos el n de horas segn el rango. fF = c2.getTime(); //Volvemos a inicializar las variables, a partir de la nueva fecha inicial. aux = line.substring(line.indexOf("\t") + 1); aux = aux.substring(0, aux.indexOf(" ")); max = min = sum = Float.parseFloat(aux); num = 1; } else { } //Si es false, seguimos leyendo los valores, y calculando las estadsticas. } //Debemos guardar lo que quede en estadisticas, porque se puede dar el caso de que no se cojan //intervalos exactos, y al terminar de leer el fichero, podemos estar en la mitad de 1 intervalo. guardarEstadisticas(fechaI); } 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(); } } }
From source file:org.apache.qpid.server.security.access.config.PlainConfiguration.java
@Override public RuleSet load() { RuleSet ruleSet = super.load(); File file = getFile();// w ww . j a va 2 s .c om FileReader fileReader = null; try { if (_logger.isDebugEnabled()) { _logger.debug("About to load ACL file " + file); } fileReader = new FileReader(file); _st = new StreamTokenizer(new BufferedReader(fileReader)); _st.resetSyntax(); // setup the tokenizer _st.commentChar(COMMENT); // single line comments _st.eolIsSignificant(true); // return EOL as a token _st.ordinaryChar('='); // equals is a token _st.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) _st.quoteChar('"'); // double quote _st.quoteChar('\''); // single quote _st.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly _st.wordChars('a', 'z'); // unquoted token characters [a-z] _st.wordChars('A', 'Z'); // [A-Z] _st.wordChars('0', '9'); // [0-9] _st.wordChars('_', '_'); // underscore _st.wordChars('-', '-'); // dash _st.wordChars('.', '.'); // dot _st.wordChars('*', '*'); // star _st.wordChars('@', '@'); // at _st.wordChars(':', ':'); // colon // parse the acl file lines Stack<String> stack = new Stack<String>(); int current; do { current = _st.nextToken(); switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, getLine())); } // check for and parse optional initial number for ACL lines Integer number = null; if (StringUtils.isNumeric(first)) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (StringUtils.equalsIgnoreCase(ACL, first)) { parseAcl(number, stack); } else if (number == null) { if (StringUtils.equalsIgnoreCase("GROUP", first)) { throw new IllegalConfigurationException(String.format( "GROUP keyword not supported. Groups should defined via a Group Provider, not in the ACL file.", getLine())); } else if (StringUtils.equalsIgnoreCase(CONFIG, first)) { parseConfig(stack); } else { throw new IllegalConfigurationException( String.format(UNRECOGNISED_INITIAL_MSG, first, getLine())); } } else { throw new IllegalConfigurationException( String.format(NUMBER_NOT_ALLOWED_MSG, first, getLine())); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(_st.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(_st.sval); // token break; default: if (_st.ttype == CONTINUATION) { int next = _st.nextToken(); if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line beacuse we ate the EOL) throw new IllegalConfigurationException( String.format(PREMATURE_CONTINUATION_MSG, getLine() + 1)); } else if (_st.ttype == '\'' || _st.ttype == '"') { stack.push(_st.sval); // quoted token } else { stack.push(Character.toString((char) _st.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, getLine())); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, getLine()), iae); } catch (FileNotFoundException fnfe) { throw new IllegalConfigurationException(String.format(CONFIG_NOT_FOUND_MSG, file.getName()), fnfe); } catch (IOException ioe) { throw new IllegalConfigurationException(String.format(CANNOT_LOAD_MSG, file.getName()), ioe); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { throw new IllegalConfigurationException(String.format(CANNOT_CLOSE_MSG, file.getName()), e); } } } return ruleSet; }
From source file:com.example.sensingapp.SensingApp.java
private void preconfigSetting() { String sAppFolder = ""; String sExistingProjectNameFilePath = ""; String sExistingUsernameFilePath = ""; String sExistingLabelFilePath = ""; File flFolder, flFile;/*from w ww . j av a2 s . c o m*/ FileReader fr; BufferedReader br; String sLine = ""; // Check whether SD Card has been plugged in if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { sAppFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getString(R.string.app_folder); flFolder = new File(sAppFolder); //Check whether /mnt/sdcard/Sensing/ exists if (!flFolder.exists()) { //Does not exist, create it if (flFolder.mkdir()) { } else { //Failed to create Toast.makeText(getApplicationContext(), "SD Card is not accessible!", Toast.LENGTH_SHORT) .show(); return; } } m_sSettingFoler = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getString(R.string.app_folder) + File.separator + getString(R.string.setting_folder); flFolder = new File(m_sSettingFoler); //Check whether /mnt/sdcard/Sensing/Setting/ exists if (!flFolder.exists()) { //Does not exist, create it if (flFolder.mkdir()) { } else { //Failed to create Toast.makeText(getApplicationContext(), "SD Card is not accessible!", Toast.LENGTH_SHORT) .show(); return; } } else { sExistingProjectNameFilePath = m_sSettingFoler + File.separator + m_sExistingProjectNameFileName; flFile = new File(sExistingProjectNameFilePath); if (flFile.exists()) { //Derive existing project names try { fr = new FileReader(sExistingProjectNameFilePath); br = new BufferedReader(fr); while ((sLine = br.readLine()) != null) { m_lstExistingProjectName.add(sLine); } fr.close(); } catch (Exception e) { } } sExistingUsernameFilePath = m_sSettingFoler + File.separator + m_sExistingUsernameFileName; flFile = new File(sExistingUsernameFilePath); if (flFile.exists()) { //Derive existing usernames try { fr = new FileReader(sExistingUsernameFilePath); br = new BufferedReader(fr); while ((sLine = br.readLine()) != null) { m_lstExistingUsername.add(sLine); } fr.close(); } catch (Exception e) { } } sExistingLabelFilePath = m_sSettingFoler + File.separator + m_sExistingLabelFileName; flFile = new File(sExistingLabelFilePath); if (flFile.exists()) { //Derive existing labels try { fr = new FileReader(sExistingLabelFilePath); br = new BufferedReader(fr); while ((sLine = br.readLine()) != null) { m_lstSensorDataLabel.add(sLine); } fr.close(); } catch (Exception e) { } } } m_sSensorDataFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getString(R.string.app_folder) + File.separator + getString(R.string.sensordata_folder); flFolder = new File(m_sSensorDataFolder); //Check whether /mnt/sdcard/Sensing/SensorData/ exists if (!flFolder.exists()) { //Does not exist, create it if (flFolder.mkdir()) { } else { //Failed to create Toast.makeText(getApplicationContext(), "SD Card is not accessible!", Toast.LENGTH_SHORT) .show(); return; } } } else { //NO SD Card Toast.makeText(getApplicationContext(), "Please insert SD Card!", Toast.LENGTH_SHORT).show(); return; } }