List of usage examples for java.util Scanner nextLine
public String nextLine()
From source file:com.wsc.myexample.decisionForest.MyTestForest.java
private void testFile(String inPath, String outPath, DataConverter converter, MyDecisionForest forest, Dataset dataset, /*List<double[]> results,*/ Random rng, ResultAnalyzer analyzer) throws IOException { // create the predictions file DataOutputStream ofile = null; if (outPath != null) { ofile = new DataOutputStream(new FileOutputStream(outPath)); }//from w w w . ja va 2s.com DataInputStream input = new DataInputStream(new FileInputStream(inPath)); try { Scanner scanner = new Scanner(input); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.isEmpty()) { continue; // skip empty lines } Instance instance = converter.convert(line); if (instance == null) continue; double prediction = forest.classify(dataset, rng, instance); if (ofile != null) { ofile.writeChars(Double.toString(prediction)); // write the prediction ofile.writeChar('\n'); } // results.add(new double[] {dataset.getLabel(instance), prediction}); analyzer.addInstance(dataset.getLabelString(dataset.getLabel(instance)), new ClassifierResult(dataset.getLabelString(prediction), 1.0)); } scanner.close(); } finally { Closeables.closeQuietly(input); ofile.close(); } }
From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseClaimDao.java
private ExpenseClaimDao(Context context) { claimList = new ArrayList<ExpenseClaim>(); File file = new File(context.getFilesDir(), FILENAME); Scanner scanner = null; try {//ww w. jav a 2 s . com scanner = new Scanner(file); while (scanner.hasNextLine()) { JSONObject jo = new JSONObject(scanner.nextLine()); ExpenseClaim claim = new ExpenseClaim(); claim.setId(jo.getInt("id")); claim.setName(jo.getString("name")); claim.setDescription(jo.getString("description")); claim.setStartDate(new Date(jo.getLong("startDate"))); claim.setEndDate(new Date(jo.getLong("endDate"))); claim.setStatus(jo.getString("status")); if (maxId < claim.getId()) { maxId = claim.getId(); } claimList.add(claim); } } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } maxId++; }
From source file:com.github.matthesrieke.simplebroker.SimpleBrokerServlet.java
protected String readContent(HttpServletRequest req) throws IOException { String enc = req.getCharacterEncoding(); Scanner sc = new Scanner(req.getInputStream(), enc == null ? "utf-8" : enc); StringBuilder sb = new StringBuilder(); while (sc.hasNext()) { sb.append(sc.nextLine()); }//from w w w .j av a 2 s . c o m sc.close(); return sb.toString(); }
From source file:com.mgmtp.perfload.perfalyzer.binning.ErrorCountBinningStragegy.java
@Override public void binData(final Scanner scanner, final WritableByteChannel destChannel) throws IOException { BinManager binManager = new BinManager(startOfFirstBin, PerfAlyzerConstants.BIN_SIZE_MILLIS_30_SECONDS); while (scanner.hasNextLine()) { tokenizer.reset(scanner.nextLine()); String[] tokens = tokenizer.getTokenArray(); long timestampMillis = Long.parseLong(tokens[0]); boolean isError = "ERROR".equals(tokens[MEASURING_NORMALIZED_COL_RESULT]); if (isError) { String errorMsg = tokens[MEASURING_NORMALIZED_COL_ERROR_MSG]; MutableInt errorsByTypeCounter = errorsByType.get(errorMsg); if (errorsByTypeCounter == null) { errorsByTypeCounter = new MutableInt(); errorsByType.put(errorMsg, errorsByTypeCounter); }/* w w w . j ava 2s . c om*/ errorsByTypeCounter.increment(); binManager.addValue(timestampMillis); } } binManager.toCsv(destChannel, "seconds", "count", intNumberFormat); }
From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseItemDao.java
private ExpenseItemDao(Context context) { itemList = new ArrayList<ExpenseItem>(); File file = new File(context.getFilesDir(), FILENAME); Scanner scanner = null; try {//from ww w . ja v a 2 s . c o m scanner = new Scanner(file); while (scanner.hasNextLine()) { JSONObject jo = new JSONObject(scanner.nextLine()); ExpenseItem item = new ExpenseItem(); item.setId(jo.getInt("id")); item.setClaimId(jo.getInt("claimId")); item.setCategory(jo.getString("category")); item.setDescription(jo.getString("description")); item.setDate(new Date(jo.getLong("date"))); item.setAmount(jo.getDouble("amount")); item.setUnit(jo.getString("unit")); if (maxId < item.getId()) { maxId = item.getId(); } itemList.add(item); } } catch (Exception e) { e.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } maxId++; }
From source file:eu.planets_project.pp.plato.services.action.planets.PlanetsMigrationService.java
private List<Parameter> getParameters(String configSettings) { List<Parameter> serviceParams = new ArrayList<Parameter>(); if (configSettings == null) { return serviceParams; }//from w w w . j ava2 s . c o m Scanner scanner = new Scanner(configSettings); int index; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if ((index = line.indexOf('=')) > 0) { String name = line.substring(0, index); String value = line.substring(index + 1); if (name.length() > 0 && value.length() > 0) { serviceParams.add((new Parameter.Builder(name.trim(), value.trim()).build())); } } } return serviceParams; }
From source file:com.joliciel.talismane.lexicon.LexiconSerializer.java
public void serializeLexicons(String[] args) { try {/*from w w w.j av a 2 s. co m*/ String lexiconDirPath = ""; String outDirPath = ""; String posTagSetPath = ""; String lexiconPatternPath = ""; for (String arg : args) { int equalsPos = arg.indexOf('='); String argName = arg.substring(0, equalsPos); String argValue = arg.substring(equalsPos + 1); if (argName.equals("lexiconDir")) lexiconDirPath = argValue; else if (argName.equals("outDir")) outDirPath = argValue; else if (argName.equals("posTagSet")) posTagSetPath = argValue; else if (argName.equals("lexiconPattern")) lexiconPatternPath = argValue; else throw new RuntimeException("Unknown argument: " + argName); } if (lexiconDirPath.length() == 0) throw new RuntimeException("Missing argument: lexiconDir"); if (outDirPath.length() == 0) throw new RuntimeException("Missing argument: outDir"); if (posTagSetPath.length() == 0) throw new RuntimeException("Missing argument: posTagSet"); if (lexiconPatternPath.length() == 0) throw new RuntimeException("Missing argument: lexiconPattern"); File outDir = new File(outDirPath); outDir.mkdirs(); TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance(); PosTaggerService posTaggerService = talismaneServiceLocator.getPosTaggerServiceLocator() .getPosTaggerService(); File posTagSetFile = new File(posTagSetPath); PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile); TalismaneSession.setPosTagSet(posTagSet); File lexiconDir = new File(lexiconDirPath); File[] lexiconFiles = lexiconDir.listFiles(); File lexiconPatternFile = new File(lexiconPatternPath); Scanner lexiconPatternScanner = new Scanner(lexiconPatternFile); String regex = null; if (lexiconPatternScanner.hasNextLine()) { regex = lexiconPatternScanner.nextLine(); } RegexLexicalEntryReader lexicalEntryReader = new RegexLexicalEntryReader(this.getMorphologyReader()); lexicalEntryReader.setRegex(regex); for (File inFile : lexiconFiles) { LOG.debug("Serializing: " + inFile.getName()); LexiconFile lexiconFile = new LexiconFile(lexicalEntryReader, inFile); lexiconFile.setPosTagSet(posTagSet); FileOutputStream fos = null; ObjectOutputStream out = null; String fileNameBase = inFile.getName(); if (fileNameBase.indexOf('.') >= 0) { fileNameBase = fileNameBase.substring(0, fileNameBase.lastIndexOf('.')); File outFile = new File(outDir, fileNameBase + ".obj"); try { fos = new FileOutputStream(outFile); out = new ObjectOutputStream(fos); try { out.writeObject(lexiconFile); } finally { out.flush(); out.close(); } } catch (IOException ioe) { throw new RuntimeException(ioe); } } } } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:htsjdk.samtools.tabix.IndexingFeatureWriterNGTest.java
@Test public void blockCompressFile() throws FileNotFoundException { String file = "/home/sol/Downloads/test.chain.gff"; String out = "/home/sol/Downloads/t.bgz"; BlockCompressedOutputStream bcos = new BlockCompressedOutputStream(new File(out)); PrintStream ps = new PrintStream(bcos); Scanner scan = new Scanner(new File(file)); while (scan.hasNext()) { ps.println(scan.nextLine()); }// ww w . j ava 2 s .c o m ps.close(); }
From source file:com.yahoo.ycsb.bulk.hbase.RangePartitioner.java
private synchronized Text[] getCutPoints() throws IOException { if (cutPointArray == null) { String cutFileName = conf.get(CUTFILE_KEY); Path[] cf = DistributedCache.getLocalCacheFiles(conf); if (cf != null) { for (Path path : cf) { if (path.toUri().getPath().endsWith(cutFileName.substring(cutFileName.lastIndexOf('/')))) { TreeSet<Text> cutPoints = new TreeSet<Text>(); Scanner in = new Scanner(new BufferedReader(new FileReader(path.toString()))); try { while (in.hasNextLine()) cutPoints.add(new Text(Base64.decodeBase64(in.nextLine().getBytes()))); } finally { in.close();/* w ww .jav a2s .c o m*/ } cutPointArray = cutPoints.toArray(new Text[cutPoints.size()]); break; } } } if (cutPointArray == null) throw new FileNotFoundException(cutFileName + " not found in distributed cache"); } return cutPointArray; }
From source file:org.sasabus.export2Freegis.network.SubscriptionManager.java
public boolean subscribe() throws IOException { for (int i = 0; i < SUBFILEARRAY.length; ++i) { Scanner sc = new Scanner(new File(SUBFILEARRAY[i])); String subscriptionstring = ""; while (sc.hasNextLine()) { subscriptionstring += sc.nextLine(); }//from w ww .j a va 2 s.c om sc.close(); SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ"); Date d = new Date(); String timestamp = date_date.format(d) + "T" + date_time.format(d); timestamp = timestamp.substring(0, timestamp.length() - 2) + ":" + timestamp.substring(timestamp.length() - 2); Calendar c = Calendar.getInstance(); c.setTime(d); c.add(Calendar.DATE, 1); d = c.getTime(); String valid_until = date_date.format(d) + "T" + date_time.format(d); valid_until = valid_until.substring(0, valid_until.length() - 2) + ":" + valid_until.substring(valid_until.length() - 2); subscriptionstring = subscriptionstring.replaceAll(":timestamp_valid", valid_until); subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp); String requestString = "http://" + this.address + ":" + this.portnumber_sender + "/TmEvNotificationService/gms/subscription.xml"; HttpPost subrequest = new HttpPost(requestString); StringEntity requestEntity = new StringEntity(subscriptionstring, ContentType.create("text/xml", "ISO-8859-1")); CloseableHttpClient httpClient = HttpClients.createDefault(); subrequest.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(subrequest); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { try { System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode()); System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase()); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responsebody = EntityUtils.toString(responseEntity); System.out.println(responsebody); } } finally { response.close(); httpClient.close(); } return false; } System.out.println("Subscription of " + SUBFILEARRAY[i]); } return true; }