List of usage examples for java.util Scanner useDelimiter
public Scanner useDelimiter(String pattern)
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
public static Float[] subsetFloatVector(InputStream in, int column, int numCases) { Float[] retVector = new Float[numCases]; Scanner scanner = new Scanner(in); scanner.useDelimiter("\\n"); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { if (scanner.hasNext()) { String[] line = (scanner.next()).split("\t", -1); // Verified: new Float("nan") works correctly, // resulting in Float.NaN; // Float("[+-]Inf") doesn't work however; // (the constructor appears to be expecting it // to be spelled as "Infinity", "-Infinity", etc. if ("inf".equalsIgnoreCase(line[column]) || "+inf".equalsIgnoreCase(line[column])) { retVector[caseIndex] = java.lang.Float.POSITIVE_INFINITY; } else if ("-inf".equalsIgnoreCase(line[column])) { retVector[caseIndex] = java.lang.Float.NEGATIVE_INFINITY; } else if (line[column] == null || line[column].equals("")) { // missing value: retVector[caseIndex] = null; } else { try { retVector[caseIndex] = new Float(line[column]); } catch (NumberFormatException ex) { retVector[caseIndex] = null; // missing value }//www . j ava 2 s . com } } else { scanner.close(); throw new RuntimeException("Tab file has fewer rows than the stored number of cases!"); } } int tailIndex = numCases; while (scanner.hasNext()) { String nextLine = scanner.next(); if (!"".equals(nextLine)) { scanner.close(); throw new RuntimeException( "Column " + column + ": tab file has more nonempty rows than the stored number of cases (" + numCases + ")! current index: " + tailIndex + ", line: " + nextLine); } tailIndex++; } scanner.close(); return retVector; }
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
public static Double[] subsetDoubleVector(InputStream in, int column, int numCases) { Double[] retVector = new Double[numCases]; Scanner scanner = new Scanner(in); scanner.useDelimiter("\\n"); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { if (scanner.hasNext()) { String[] line = (scanner.next()).split("\t", -1); // Verified: new Double("nan") works correctly, // resulting in Double.NaN; // Double("[+-]Inf") doesn't work however; // (the constructor appears to be expecting it // to be spelled as "Infinity", "-Infinity", etc. if ("inf".equalsIgnoreCase(line[column]) || "+inf".equalsIgnoreCase(line[column])) { retVector[caseIndex] = java.lang.Double.POSITIVE_INFINITY; } else if ("-inf".equalsIgnoreCase(line[column])) { retVector[caseIndex] = java.lang.Double.NEGATIVE_INFINITY; } else if (line[column] == null || line[column].equals("")) { // missing value: retVector[caseIndex] = null; } else { try { retVector[caseIndex] = new Double(line[column]); } catch (NumberFormatException ex) { retVector[caseIndex] = null; // missing value }/*w w w . j a v a2s.co m*/ } } else { scanner.close(); throw new RuntimeException("Tab file has fewer rows than the stored number of cases!"); } } int tailIndex = numCases; while (scanner.hasNext()) { String nextLine = scanner.next(); if (!"".equals(nextLine)) { scanner.close(); throw new RuntimeException( "Column " + column + ": tab file has more nonempty rows than the stored number of cases (" + numCases + ")! current index: " + tailIndex + ", line: " + nextLine); } tailIndex++; } scanner.close(); return retVector; }
From source file:com.surevine.alfresco.esl.impl.GroupDetails.java
/** * Constructor. Create a GroupDetails within the given constraint according to the given specification * /*from w ww.ja v a2s . c o m*/ * @param specification * See the comments at the top of this class, and the unit tests, for more details * @param parentConstraint */ public GroupDetails(String specification, EnhancedSecurityConstraint parentConstraint) { // Check params look OK if (specification == null || parentConstraint == null) { throw new EnhancedSecurityException( "Both the specification and the parent constraint must be non-null to create a GroupDetails"); } // Parse out key=value,key=value pairs and use setKVPair to set relevant properties try { _constraint = parentConstraint; Scanner keyValuePair = new Scanner(specification.trim()); keyValuePair.useDelimiter("\n+"); while (keyValuePair.hasNext()) { String keyOrValueStr = keyValuePair.next().trim(); if (keyOrValueStr.equals("")) { continue; } if (LOG.isDebugEnabled()) { LOG.debug("Found Key/Value Pair: " + keyOrValueStr); } Scanner keyOrValue = new Scanner(keyOrValueStr); keyOrValue.useDelimiter("="); String key = keyOrValue.next(); LOG.debug(" Found Key: " + key); String value = keyOrValue.next(); LOG.debug(" Found Value: " + value); if (keyOrValue.hasNext()) { throw new EnhancedSecurityException("Was expecting a single '=' in [" + keyValuePair + "]"); } setKVPair(key, value); } } catch (NoSuchElementException e) { throw new EnhancedSecurityException( "The group details specification was incorrectly formatted. It should be key=value [lineBreak] key=value with no '=' charecters in the keys or values", e); } }
From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptBSearchModuleImpl.java
@Override public boolean validate(File siardDatei, File outFileSearch, String searchString) throws ExcerptBSearchException { boolean isValid = true; File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe"); String pathToGrepExe = fGrepExe.getAbsolutePath(); if (!fGrepExe.exists()) { // grep.exe existiert nicht --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath())); return false; } else {//from w w w . j a va 2s . c om File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll"); if (!fMsys10dll.exists()) { // msys-1.0.dll existiert nicht --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath())); return false; } } File tempOutFile = new File(outFileSearch.getAbsolutePath() + ".tmp"); String content = ""; String contentAll = ""; // Records aus table herausholen try { if (tempOutFile.exists()) { Util.deleteDir(tempOutFile); } /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ String name = getConfigurationService().getSearchtableName(); String folder = getConfigurationService().getSearchtableFolder(); File fSearchtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator + "schema0" + File.separator + folder + File.separator + folder + ".xml"); searchString = searchString.replaceAll("\\.", "\\.*"); try { // grep -E "REGEX-Suchbegriff" table13.xml >> output.txt String command = "cmd /c \"" + pathToGrepExe + " -E \"" + searchString + "\" " + fSearchtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\""; /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl * gehts: cmd /c\"urspruenlicher Befehl\" */ // System.out.println( command ); Process proc = null; Runtime rt = null; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name)); try { Util.switchOffConsole(); rt = Runtime.getRuntime(); proc = rt.exec(command.toString().split(" ")); // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist! // Fehleroutput holen StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // Output holen StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // Threads starten errorGobbler.start(); outputGobbler.start(); // Warte, bis wget fertig ist proc.waitFor(); Util.switchOnConsole(); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } Scanner scanner = new Scanner(tempOutFile); contentAll = ""; content = ""; contentAll = scanner.useDelimiter("\\Z").next(); scanner.close(); content = contentAll; /* im contentAll ist jetzt der Gesamtstring, dieser soll anschliessend nur noch aus den 4 * Such-Zellen und den weiteren 4 ResultateZellen bestehen -> content */ String nr1 = getConfigurationService().getcellNumber1(); String nr2 = getConfigurationService().getcellNumber2(); String nr3 = getConfigurationService().getcellNumber3(); String nr4 = getConfigurationService().getcellNumber4(); String nr5 = getConfigurationService().getcellNumberResult1(); String nr6 = getConfigurationService().getcellNumberResult2(); String nr7 = getConfigurationService().getcellNumberResult3(); String nr8 = getConfigurationService().getcellNumberResult4(); String cellLoop = ""; // Loop von 1, 2, 3 ... bis 499999. for (int i = 1; i < 500000; i++) { cellLoop = ""; cellLoop = "c" + i; if (cellLoop.equals(nr1) || cellLoop.equals(nr2) || cellLoop.equals(nr3) || cellLoop.equals(nr4) || cellLoop.equals(nr5) || cellLoop.equals(nr6) || cellLoop.equals(nr7) || cellLoop.equals(nr8)) { // wird behalten } else { String deletString = "<c" + i + ">" + ".*" + "</c" + i + ">"; content = content.replaceAll(deletString, ""); } } getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content)); getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name)); if (tempOutFile.exists()) { Util.deleteDir(tempOutFile); } contentAll = ""; content = ""; // Ende Grep } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } return isValid; }
From source file:org.callimachusproject.test.TemporaryServerFactory.java
private String readRepositoryConfigFile() throws FileNotFoundException { Scanner scanner = new Scanner(new File("etc", "callimachus-repository.ttl")); try {//ww w . ja v a 2 s .c o m return scanner.useDelimiter("\\A").next(); } finally { scanner.close(); } }
From source file:eremeykin.pete.plotter.PolarPlotterTopComponent.java
@Override public void update() { // for first rpt file if (model == null) { clear();//from w w w.j a va2 s. c om return; } File[] rptFiles = home.listFiles(filter()); // catch if there is no such file if (rptFiles.length == 0) { clear(); return; } File firstRPT = rptFiles[0]; Scanner scanner; try { scanner = new Scanner(firstRPT); scanner.useDelimiter("\\s+|\n"); } catch (FileNotFoundException ex) { clear(); return; } List<Map.Entry<Double, Double>> tmpList = new ArrayList<>(); for (int i = 0; scanner.hasNext(); i++) { String line = scanner.next(); try { double x1 = Double.valueOf(line); line = scanner.next(); double x2 = Double.valueOf(line); // System.out.println("x1=" + x1 + "\nx2=" + x2); tmpList.add(new AbstractMap.SimpleEntry<>(x1, x2)); } catch (NumberFormatException ex) { // only if it is the third or following line if (i > 1) { LOGGER.error("Error while parsing double from file: " + firstRPT.getAbsolutePath()); JOptionPane.showMessageDialog(this, "Error while parsing result file.", "Parsing error", JOptionPane.ERROR_MESSAGE); } } } if (tmpList.isEmpty()) { clear(); return; } fillData(tmpList); // fillData(tmpList, dataSeries, toleranceSeries); }
From source file:org.motechproject.mobile.imp.serivce.oxd.FormDefinitionServiceImpl.java
private String getFileContent(String fileName) { StringBuilder builder = new StringBuilder(); Scanner scanner; try {//from w w w. jav a2s. c o m scanner = new Scanner(new File(fileName)); scanner.useDelimiter("\n"); while (scanner.hasNextLine()) { builder.append(scanner.nextLine() + "\n"); } } catch (FileNotFoundException e) { e.printStackTrace(); } return builder.toString(); }
From source file:org.talend.dataprep.schema.csv.CSVFastHeaderAndTypeAnalyzer.java
/** * Performs type analysis for fields of the record at the specified index. * //from w ww . java 2s .c o m * @param i the index of the record to be analyzed. * @return the list of types of the record */ private List<Integer> setFieldType(int i) { List<Integer> result = new ArrayList<>(); String line = i < sampleLines.size() ? sampleLines.get(i) : null; if (StringUtils.isEmpty(line)) { return result; } List<String> fields = readLine(line); for (String field : fields) { Scanner scanner = new Scanner(field); scanner.useDelimiter(Character.toString(separator.getSeparator())); // called integer but we are looking for long in Java parlance if (scanner.hasNextLong()) { result.add(INTEGER); scanner.next(); } else if (scanner.hasNextDouble()) { result.add(DECIMAL); scanner.next(); } else if (scanner.hasNextBoolean()) { result.add(BOOLEAN); scanner.next(); } else { String text = scanner.hasNext() ? scanner.next() : StringUtils.EMPTY; switch (text) { case "": result.add(EMPTY); break; default: // used to detect a stable length of a field (may be it is a date or a pattern) result.add(text.length()); } } scanner.close(); } return result; }
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
public static String[] subsetStringVector(InputStream in, int column, int numCases) { String[] retVector = new String[numCases]; Scanner scanner = new Scanner(in); scanner.useDelimiter("\\n"); for (int caseIndex = 0; caseIndex < numCases; caseIndex++) { if (scanner.hasNext()) { String[] line = (scanner.next()).split("\t", -1); retVector[caseIndex] = line[column]; if ("".equals(line[column])) { // An empty string is a string missing value! // An empty string in quotes is an empty string! retVector[caseIndex] = null; } else { // Strip the outer quotes: line[column] = line[column].replaceFirst("^\\\"", ""); line[column] = line[column].replaceFirst("\\\"$", ""); // We need to restore the special characters that // are stored in tab files escaped - quotes, new lines // and tabs. Before we do that however, we need to // take care of any escaped backslashes stored in // the tab file. I.e., "foo\t" should be transformed // to "foo<TAB>"; but "foo\\t" should be transformed // to "foo\t". This way new lines and tabs that were // already escaped in the original data are not // going to be transformed to unescaped tab and // new line characters! String[] splitTokens = line[column].split(Matcher.quoteReplacement("\\\\"), -2); // (note that it's important to use the 2-argument version // of String.split(), and set the limit argument to a // negative value; otherwise any trailing backslashes // are lost.) for (int i = 0; i < splitTokens.length; i++) { splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\\""), "\""); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\t"), "\t"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\n"), "\n"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\r"), "\r"); }/*from w w w.j a va2 s . c o m*/ // TODO: // Make (some of?) the above optional; for ex., we // do need to restore the newlines when calculating UNFs; // But if we are subsetting these vectors in order to // create a new tab-delimited file, they will // actually break things! -- L.A. Jul. 28 2014 line[column] = StringUtils.join(splitTokens, '\\'); retVector[caseIndex] = line[column]; } } else { scanner.close(); throw new RuntimeException("Tab file has fewer rows than the stored number of cases!"); } } int tailIndex = numCases; while (scanner.hasNext()) { String nextLine = scanner.next(); if (!"".equals(nextLine)) { scanner.close(); throw new RuntimeException( "Column " + column + ": tab file has more nonempty rows than the stored number of cases (" + numCases + ")! current index: " + tailIndex + ", line: " + nextLine); } tailIndex++; } scanner.close(); return retVector; }