List of usage examples for java.util Scanner close
public void close()
From source file:com.bizosys.hsearch.index.IndexReaderTest.java
private void tryOut() throws Exception { Scanner in = new Scanner(System.in); String query = in.nextLine(); in.close(); QueryContext ctx = new QueryContext(acc, query); QueryResult results = null;//from www .j av a 2s. com results = IndexReader.getInstance().search(ctx); int size = (null == results) ? 0 : (null == results.teasers) ? 0 : results.teasers.length; if (0 == size) { System.out.println("<list></list>"); return; } System.out.println(results.toString()); System.out.println(IndexReader.getInstance().get(acc.name, "6EY-VF9U5uQ")); }
From source file:com.frankdye.marvelgraphws2.MarvelGraphView.java
/** * Creates a new instance of SimpleGraphView *///from ww w .ja va 2 s . com public MarvelGraphView() { try { Path fFilePath; /** * Assumes UTF-8 encoding. JDK 7+. */ String aFileName = "C:\\Users\\Frank Dye\\Desktop\\Programming Projects\\MarvelGraph\\data\\marvel_labeled_edges.tsv"; fFilePath = Paths.get(aFileName); // New code // Read words from file and put into a simulated multimap Map<String, List<String>> map1 = new HashMap<String, List<String>>(); Set<String> set1 = new HashSet<String>(); Scanner scan1 = null; try { scan1 = new Scanner(fFilePath, ENCODING.name()); while (scan1.hasNext()) { processLine(scan1.nextLine(), map1, set1); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Creating an URL object. JSONObject newObj = new JSONObject(); newObj.put("Heroes", set1); //Write out our set to a file PrintWriter fileWriter = null; try { fileWriter = new PrintWriter("heroes-json.txt", "UTF-8"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } fileWriter.println(newObj); fileWriter.close(); System.out.println(newObj); // Close our scanner scan1.close(); log("Done."); // Graph<V, E> where V is the type of the vertices // and E is the type of the edges g = new SparseMultigraph<String, String>(); // Add some vertices. From above we defined these to be type Integer. for (String s : set1) { g.addVertex(s); } for (Entry<String, List<String>> entry : map1.entrySet()) { String issue = entry.getKey(); ListIterator<String> heroes = entry.getValue().listIterator(); String firstHero = heroes.next(); while (heroes.hasNext()) { String secondHero = heroes.next(); if (!g.containsEdge(issue)) { g.addEdge(issue, firstHero, secondHero); } } } // Let's see what we have. Note the nice output from the // SparseMultigraph<V,E> toString() method // System.out.println("The graph g = " + g.toString()); // Note that we can use the same nodes and edges in two different // graphs. DijkstraShortestPath alg = new DijkstraShortestPath(g, true); Map<String, Number> distMap = new HashMap<String, Number>(); String n1 = "VOLSTAGG"; String n4 = "ROM, SPACEKNIGHT"; List<String> l = alg.getPath(n1, n4); distMap = alg.getDistanceMap(n1); System.out.println("The shortest unweighted path from " + n1 + " to " + n4 + " is:"); System.out.println(l.toString()); System.out.println("\nDistance Map: " + distMap.get(n4)); } catch (JSONException ex) { Logger.getLogger(MarvelGraphView.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ml.shifu.shifu.core.processor.InitModelProcessor.java
private Map<Integer, Data> getCountInfoMap(SourceType source, String autoTypePath) throws IOException { String outputFilePattern = autoTypePath + Path.SEPARATOR + "part-*"; if (!ShifuFileUtils.isFileExists(outputFilePattern, source)) { throw new RuntimeException("Auto type checking output file not exist."); }/*from w w w . ja va 2s . c om*/ Map<Integer, Data> distinctCountMap = new HashMap<Integer, Data>(); List<Scanner> scanners = null; try { // here only works for 1 reducer FileStatus[] globStatus = ShifuFileUtils.getFileSystemBySourceType(source) .globStatus(new Path(outputFilePattern)); if (globStatus == null || globStatus.length == 0) { throw new RuntimeException("Auto type checking output file not exist."); } scanners = ShifuFileUtils.getDataScanners(globStatus[0].getPath().toString(), source); Scanner scanner = scanners.get(0); String str = null; while (scanner.hasNext()) { str = scanner.nextLine().trim(); if (str.contains(TAB_STR)) { String[] splits1 = str.split(TAB_STR); String[] splits2 = splits1[1].split(":", -1); distinctCountMap.put(Integer.valueOf(splits1[0]), new Data(Long.valueOf(splits2[0]), Long.valueOf(splits2[1]), Long.valueOf(splits2[2]), Long.valueOf(splits2[3]), splits2[4].split(","))); } } return distinctCountMap; } finally { if (scanners != null) { for (Scanner scanner : scanners) { if (scanner != null) { scanner.close(); } } } } }
From source file:com.wikitude.phonegap.WikitudePlugin.java
/** * // www .ja va 2s .c om * @return true if device chip has neon-command support */ private boolean hasNeonSupport() { /* Read cpu info */ FileInputStream fis; try { fis = new FileInputStream("/proc/cpuinfo"); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return false; } Scanner scanner = new Scanner(fis); boolean neonSupport = false; try { while (scanner.hasNextLine()) { if (!neonSupport && (scanner.findInLine("neon") != null)) { neonSupport = true; } scanner.nextLine(); } } catch (Exception e) { Log.i("Wikitudeplugin", "error while getting info about neon support" + e.getMessage()); e.printStackTrace(); } finally { scanner.close(); } return neonSupport; }
From source file:net.ftb.util.DownloadUtils.java
/** * Checks the file for corruption./*from w w w .j av a2s. c o m*/ * @param file - File to check * @param url - base url to grab md5 with old method * @return boolean representing if it is valid * @throws IOException */ public static boolean backupIsValid(File file, String url) throws IOException { Logger.logInfo("Issue with new md5 method, attempting to use backup method."); String content = null; Scanner scanner = null; String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer())) ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer()) : Locations.masterRepo; resolved += "/md5/FTB2/" + url; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); int response = connection.getResponseCode(); if (response == 200) { scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); } if (response != 200 || (content == null || content.isEmpty())) { for (String server : backupServers.values()) { resolved = "http://" + server + "/md5/FTB2/" + url.replace("/", "%5E"); connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); response = connection.getResponseCode(); if (response == 200) { scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); if (content != null && !content.isEmpty()) { break; } } } } } catch (IOException e) { } finally { connection.disconnect(); if (scanner != null) { scanner.close(); } } String result = fileMD5(file); Logger.logInfo("Local: " + result.toUpperCase()); Logger.logInfo("Remote: " + content.toUpperCase()); return content.equalsIgnoreCase(result); }
From source file:Balo.MainFram.java
public void getDataFileToJTable() { String fileNameDefined = "src/Balo/Data_3.csv"; File file = new File(fileNameDefined); int i = 0;/*www . java 2 s.c om*/ dvDynamic[0] = new Dovat(); //Get value from csv file try { Scanner inputStream = new Scanner(file); inputStream.useDelimiter(","); while (inputStream.hasNext()) { dvDynamic[i + 1] = dvGreedy[i] = new Dovat(); dvDynamic[i + 1].ten = dvGreedy[i].ten = inputStream.next().trim(); dvDynamic[i + 1].soluong = dvGreedy[i].soluong = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].giatri = dvGreedy[i].giatri = Integer.valueOf(inputStream.next().trim()); dvDynamic[i + 1].trongluong = dvGreedy[i].trongluong = Integer.valueOf(inputStream.next().trim()); i++; } //Set number of Items numOfItem = i; //Get weight bag weightBag = Integer.parseInt(TextW.getText()); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } //Set value for JTable for (int item = 0; item < numOfItem; item++) { Object[] row = new Object[4]; row[0] = dvGreedy[item].ten; row[1] = dvGreedy[item].soluong; row[2] = dvGreedy[item].giatri; row[3] = dvGreedy[item].trongluong; model.addRow(row); } }
From source file:com.amazon.sqs.javamessaging.AmazonSQSExtendedClient.java
private String getTextFromS3(String s3BucketName, String s3Key) { GetObjectRequest getObjectRequest = new GetObjectRequest(s3BucketName, s3Key); String embeddedText = null;/*from w ww .jav a 2 s .c om*/ S3Object obj = null; try { obj = clientConfiguration.getAmazonS3Client().getObject(getObjectRequest); } catch (AmazonServiceException e) { String errorMessage = "Failed to get the S3 object which contains the message payload. Message was not received."; LOG.error(errorMessage, e); throw new AmazonServiceException(errorMessage, e); } catch (AmazonClientException e) { String errorMessage = "Failed to get the S3 object which contains the message payload. Message was not received."; LOG.error(errorMessage, e); throw new AmazonClientException(errorMessage, e); } try { InputStream objContent = obj.getObjectContent(); java.util.Scanner objContentScanner = new java.util.Scanner(objContent, "UTF-8"); objContentScanner.useDelimiter("\\A"); embeddedText = objContentScanner.hasNext() ? objContentScanner.next() : ""; objContentScanner.close(); objContent.close(); } catch (IOException e) { String errorMessage = "Failure when handling the message which was read from S3 object. Message was not received."; LOG.error(errorMessage, e); throw new AmazonClientException(errorMessage, e); } return embeddedText; }
From source file:com.github.pffy.chinese.freq.ChineseFrequency.java
private void analyze() { int inputCount = 0; int removedCount = 0; int hanziCount = 0; int uniqueHanziCount = 0; int processedCount = 0; int freq = 0; String csvOutput = this.HEADER_ROW_CSV; String tsvOutput = this.HEADER_ROW_TSV; String txtOutput = this.HEADER_ROW_TXT; String csv, tsv, txt;//from w w w .ja v a 2 s. co m String str, input, pinyin, hanzi; Scanner sc; List<String> hanziList; Map<String, Integer> freqMap; JSONObject hpdx; String[] arr; Set<String> unmappedCharacters; hpdx = this.hpdx; input = this.input; inputCount = input.length(); input = retainHanzi(input); removedCount = inputCount - input.length(); hanziCount = input.length(); sc = new Scanner(input); sc.useDelimiter(""); hanziList = new ArrayList<String>(); freqMap = new HashMap<String, Integer>(); // counts occurrences while (sc.hasNext()) { str = sc.next(); hanziList.add(str); if (freqMap.containsKey(str)) { freqMap.put(str, (Integer) freqMap.get(str).intValue() + 1); } else { freqMap.put(str, 1); } } // done with Scanner sc.close(); uniqueHanziCount = freqMap.keySet().size(); SortedMap<String, String> freqTreeMap = new TreeMap<String, String>(Collections.reverseOrder()); unmappedCharacters = new HashSet<String>(); for (Entry<String, Integer> counts : freqMap.entrySet()) { try { hanzi = counts.getKey(); pinyin = hpdx.getString(hanzi); } catch (JSONException je) { // add this unmapped character to the list unmappedCharacters.add(counts.getKey()); // not idx mapped yet. that's ok. move on. continue; } if (pinyin.isEmpty()) { // if character is unmapped in idx, do not process. continue; } freq = counts.getValue(); freqTreeMap.put(String.format("%" + this.PADSIZE_FREQ + "s", freq).replace(' ', '0') + "-" + hanzi + "-" + pinyin, hanzi + "," + pinyin + "," + freq); processedCount++; } // outputs for (Entry<String, String> outputs : freqTreeMap.entrySet()) { csv = this.CRLF + outputs.getValue(); csvOutput += csv; tsv = csv.replaceAll(",", "\t"); tsvOutput += tsv; arr = csv.split(","); // arr[0] is hanzi. arr[1] is pinyin. arr[2] is freq. txt = padSummary(arr[0] + " [" + arr[1] + "]", this.PADSIZE_SUMMARY + 1) + arr[2]; txtOutput += txt; } // cleanup csvOutput = csvOutput.trim(); tsvOutput = tsvOutput.trim(); txtOutput = txtOutput.trim(); // post-process this.csvOutput = csvOutput; this.tsvOutput = tsvOutput; this.txtOutput = txtOutput; // counts this.inputCount = inputCount; this.removedCount = removedCount; this.hanziCount = hanziCount; this.uniqueHanziCount = uniqueHanziCount; this.processedCount = processedCount; this.unmappedCharacters = unmappedCharacters; // summary String summaryString = ""; summaryString += padSummary(this.MSG_TOTAL_COUNT, this.PADSIZE_SUMMARY) + inputCount; summaryString += this.CRLF + padSummary(this.MSG_REMOVED_COUNT, this.PADSIZE_SUMMARY) + removedCount; summaryString += this.CRLF + padSummary(this.MSG_HANZI_COUNT, this.PADSIZE_SUMMARY) + hanziCount; summaryString += this.CRLF + padSummary(this.MSG_UNIQUE_COUNT, this.PADSIZE_SUMMARY) + uniqueHanziCount; summaryString += this.CRLF + padSummary(this.MSG_PROCESSED_COUNT, this.PADSIZE_SUMMARY) + processedCount; this.summary = summaryString; }
From source file:dsfixgui.view.DSFGraphicsPane.java
private String getFPSFixKey() { File fpsFixCfg = new File(ui.getDataFolder() + "\\" + FPS_FIX_FILES[1]); if (fpsFixCfg.exists()) { try {//from w w w .j av a 2 s. c o m Scanner fpsFixKeyScanner = new Scanner(fpsFixCfg); while (fpsFixKeyScanner.hasNextLine()) { String line = fpsFixKeyScanner.nextLine(); if (line.startsWith("Key=")) { fpsFixKeyScanner.close(); return line.substring(line.indexOf("Key=") + 4); } } } catch (FileNotFoundException ex) { //Logger.getLogger(DSFGraphicsPane.class.getName()).log(Level.SEVERE, null, ex); return null; } } else { return null; } return null; }