List of usage examples for java.util Scanner close
public void close()
From source file:ehospital.Principal.java
private void btn_cargar_ambuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cargar_ambuMouseClicked // TODO add your handling code here: Scanner sc = null; File archivo2;/*www . j a v a 2s . c om*/ try { archivo2 = new File("./Ambulancia.txt"); sc = new Scanner(archivo2); sc.useDelimiter(","); while (sc.hasNext()) { Ambulancias ambu = new Ambulancias(sc.next(), sc.nextInt(), sc.nextInt(), new Lugar(sc.next()), sc.nextBoolean()); lista_ambu.add(ambu); } JOptionPane.showMessageDialog(null, "Ambulancias Cargadas"); } catch (Exception e) { } finally { sc.close(); } System.out.println(lista_ambu.toString()); }
From source file:com.smi.travel.monitor.MonitorAmadeus.java
@Override void buildContentList(String file) { String pathFile = this.monitorDirectory + file; Path fFilePath;/*from w w w .j av a 2 s . c o m*/ fFilePath = Paths.get(pathFile); boolean pullSectionPassenger = false; StringBuffer passengerData = new StringBuffer(); String key = null; sectionData = new MultiValueMap(); Scanner scanner = null; try { scanner = new Scanner(fFilePath, ENCODING.name()); while (scanner.hasNextLine()) { String line = scanner.nextLine(); // System.out.println("Read** " + line); // if (line.equalsIgnoreCase("END")) { if (line.startsWith("END")) { // System.out.println("Found ENDX and goto Save data"); sectionData.put("I-", passengerData.toString()); break; } //check whether in SectionPassenger if (pullSectionPassenger && (line.charAt(0) == 'I' && line.charAt(1) == '-')) { // found new passenger. Save old one sectionData.put("I-", passengerData.toString()); passengerData = new StringBuffer(); } else if (pullSectionPassenger) { if (line.charAt(1) == '-') { key = line.substring(0, 2); sectionData.put(key, line); } passengerData.append(line); passengerData.append("\n"); continue; } // System.out.println(line); if (line.charAt(0) == 'I' && line.charAt(1) == '-') { //pull all passenger data. pullSectionPassenger = true; passengerData.append(line); passengerData.append("\n"); continue; } else if (line.charAt(1) == '-') { key = line.substring(0, 2); } else { key = line.substring(0, 3); } sectionData.put(key, line); // System.out.println("Key " + key + " ,[" + line); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (scanner != null) { scanner.close(); } } }
From source file:ehospital.Principal.java
private void btn_cargar_paramMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cargar_paramMouseClicked // TODO add your handling code here: Scanner sc = null; File archivo2;/*from w w w . j av a 2s. c om*/ try { archivo2 = new File("./Paramedicos.txt"); sc = new Scanner(archivo2); sc.useDelimiter(","); while (sc.hasNext()) { Paramedicos param = new Paramedicos(sc.next(), sc.nextInt(), sc.nextInt(), sc.next(), new Lugar(sc.next()), sc.nextBoolean()); lista_param.add(param); } JOptionPane.showMessageDialog(null, "Paramedicos Cargadas"); } catch (Exception e) { } finally { sc.close(); } System.out.println(lista_param.toString()); }
From source file:HackathonSupporter.java
@Override /**// w w w.j a v a 2 s .co m * Returns the banner after searching in the file. * @param advId The forced advertisement id you get from GET request * @param width the requested width * @param height the request height * @param segmentId the segment ID you get by reading the cookie * @context object of ServletContext which is needed to read the config.properties file */ public String readFromFile(String advId, int width, int height, int segmentId, ServletContext context, int callingFlag) { File file = null; Scanner fis = null; String banner = null; try { //read the filename and mappingFilename form the config.properties file Properties prop = new Properties(); if (callingFlag == 0) { prop.load(new InputStreamReader(context.getResourceAsStream("/WEB-INF/config.properties"))); } else if (callingFlag == 1) { prop.load(new FileReader( "/home/sankalpkulshrestha/NetBeansProjects/AdServer/web/WEB-INF/config.properties")); } else { return DEFAULT_BANNER; } //filename contains the list of advId, width, height, banner,segmentID. The filename is input.txt String filename = prop.getProperty("filename"); //mappingFilename contains the mapping of the advId and the default banner address String mappingFilename = prop.getProperty("mappingFilename"); file = new File(filename); fis = new Scanner(file); String line = null; //read the each line of input.txt, split it by comma and store it in param String array String[] param = new String[5]; //w and h hold the width and height respectively. //flag keeps track of whether a corresponding advId is found for a segnment ID, in case the advId is null int w = -1, h = -1, flag = 0; while (fis.hasNextLine()) { //read each line and split by comma line = fis.nextLine(); param = line.split(","); //read the width and height from the input.txt w = Integer.parseInt(param[1]); h = Integer.parseInt(param[2]); //in case we are not getting and forced advertisement ID, we keep searching for the corresponding advId is found for a segnment ID if ((advId == null || advId.length() == 0) && flag == 0 && segmentId == Integer.parseInt(param[4])) { flag = 1; advId = param[0]; } //in case segment ID is not 0 and segmentId is same as the segment ID found from the file of same width //and height as the requested width and height, we set the corresponding banner from the file and break away if (segmentId != 0 && segmentId == Integer.parseInt(param[4]) && w == width && h == height) { banner = param[3]; break; } } //close the input.txt file if (fis != null) { fis.close(); } //if till now the banner is still null and the advId is not null //then we check the mapping.txt file for finding the default banner of the campaign //the advId points to if (banner == null && advId != null) { File file2 = new File(mappingFilename); Scanner fis2 = null; fis2 = new Scanner(file2); param = new String[2]; while (fis2.hasNextLine()) { line = fis2.nextLine(); param = line.split(","); if (param[0].equals(advId)) { banner = param[1]; break; } } //close the mapping.txt file if (fis2 != null) { fis2.close(); } } else if (banner == null && advId == null) { //in case the banner is null and the advId is null, we return the default banner return DEFAULT_BANNER; } } catch (IOException e) { //in case of any exception, we return the default banner return DEFAULT_BANNER; } finally { //close the file if (fis != null) { fis.close(); } } return banner; }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java
private File decodeHeader(BufferedInputStream stream) throws IOException { File tempPORfile = null;//from w w w .j a v a 2 s . c om if (stream == null) { throw new IllegalArgumentException("file == null!"); } byte[] headerByes = new byte[POR_HEADER_SIZE]; if (stream.markSupported()) { stream.mark(1000); } int nbytes = stream.read(headerByes, 0, POR_HEADER_SIZE); //printHexDump(headerByes, "hex dump of the byte-array"); if (nbytes == 0) { throw new IOException("decodeHeader: reading failure"); } else if (nbytes < 491) { // Size test: by defnition, it must have at least // 491-byte header, i.e., the file size less than this threshold // is not a POR file dbgLog.fine("this file is NOT spss-por type"); throw new IllegalArgumentException("file is not spss-por type"); } // rewind the current reading position back to the beginning if (stream.markSupported()) { stream.reset(); } // line-terminating characters are usually one or two by defnition // however, a POR file saved by a genuine SPSS for Windows // had a three-character line terminator, i.e., failed to remove the // original file's one-character terminator when it was opened, and // saved it with the default two-character terminator without // removing original terminators. So we have to expect such a rare // case // // terminator // windows [0D0A]=> [1310] = [CR/LF] // unix [0A] => [10] // mac [0D] => [13] // 3char [0D0D0A]=> [131310] spss for windows rel 15 // // terminating characters should be found at the following // column positions[counting from 0]: // unix case: [0A] : [80], [161], [242], [323], [404], [485] // windows case: [0D0A] : [81], [163], [245], [327], [409], [491] // : [0D0D0A] : [82], [165], [248], [331], [414], [495] // convert b into a ByteBuffer ByteBuffer buff = ByteBuffer.wrap(headerByes); byte[] nlch = new byte[36]; int pos1; int pos2; int pos3; int ucase = 0; int wcase = 0; int mcase = 0; int three = 0; int nolines = 6; int nocols = 80; for (int i = 0; i < nolines; ++i) { int baseBias = nocols * (i + 1); // 1-char case pos1 = baseBias + i; buff.position(pos1); dbgLog.finer("\tposition(1)=" + buff.position()); int j = 6 * i; nlch[j] = buff.get(); if (nlch[j] == 10) { ucase++; } else if (nlch[j] == 13) { mcase++; } // 2-char case pos2 = baseBias + 2 * i; buff.position(pos2); dbgLog.finer("\tposition(2)=" + buff.position()); nlch[j + 1] = buff.get(); nlch[j + 2] = buff.get(); // 3-char case pos3 = baseBias + 3 * i; buff.position(pos3); dbgLog.finer("\tposition(3)=" + buff.position()); nlch[j + 3] = buff.get(); nlch[j + 4] = buff.get(); nlch[j + 5] = buff.get(); dbgLog.finer(i + "-th iteration position =" + nlch[j] + "\t" + nlch[j + 1] + "\t" + nlch[j + 2]); dbgLog.finer(i + "-th iteration position =" + nlch[j + 3] + "\t" + nlch[j + 4] + "\t" + nlch[j + 5]); if ((nlch[j + 3] == 13) && (nlch[j + 4] == 13) && (nlch[j + 5] == 10)) { three++; } else if ((nlch[j + 1] == 13) && (nlch[j + 2] == 10)) { wcase++; } buff.rewind(); } boolean windowsNewLine = true; if (three == nolines) { windowsNewLine = false; // lineTerminator = "0D0D0A" } else if ((ucase == nolines) && (wcase < nolines)) { windowsNewLine = false; // lineTerminator = "0A" } else if ((ucase < nolines) && (wcase == nolines)) { windowsNewLine = true; //lineTerminator = "0D0A" } else if ((mcase == nolines) && (wcase < nolines)) { windowsNewLine = false; //lineTerminator = "0D" } buff.rewind(); int PORmarkPosition = POR_MARK_POSITION_DEFAULT; if (windowsNewLine) { PORmarkPosition = PORmarkPosition + 5; } else if (three == nolines) { PORmarkPosition = PORmarkPosition + 10; } byte[] pormark = new byte[8]; buff.position(PORmarkPosition); buff.get(pormark, 0, 8); String pormarks = new String(pormark); //dbgLog.fine("pormark =>" + pormarks + "<-"); dbgLog.fine( "pormark[hex: 53 50 53 53 50 4F 52 54 == SPSSPORT] =>" + new String(Hex.encodeHex(pormark)) + "<-"); if (pormarks.equals(POR_MARK)) { dbgLog.fine("POR ID toke test: Passed"); init(); smd.getFileInformation().put("mimeType", MIME_TYPE); smd.getFileInformation().put("fileFormat", MIME_TYPE); } else { dbgLog.fine("this file is NOT spss-por type"); throw new IllegalArgumentException("decodeHeader: POR ID token was not found"); } // save the POR file without new line characters FileOutputStream fileOutPOR = null; Writer fileWriter = null; // Scanner class can handle three-character line-terminator Scanner porScanner = null; try { tempPORfile = File.createTempFile("tempPORfile.", ".por"); fileOutPOR = new FileOutputStream(tempPORfile); fileWriter = new BufferedWriter(new OutputStreamWriter(fileOutPOR, "utf8")); porScanner = new Scanner(stream); // Because 64-bit and 32-bit machines decode POR's first 40-byte // sequence differently, the first 5 leader lines are skipped from // the new-line-stripped file int lineCounter = 0; while (porScanner.hasNextLine()) { lineCounter++; if (lineCounter <= 5) { String line = porScanner.nextLine().toString(); dbgLog.fine("line=" + lineCounter + ":" + line.length() + ":" + line); } else { fileWriter.write(porScanner.nextLine().toString()); } } } finally { try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException ex) { ex.printStackTrace(); } if (porScanner != null) { porScanner.close(); } } return tempPORfile; }
From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java
private File decodeHeader(BufferedInputStream stream) throws IOException { dbgLog.fine("decodeHeader(): start"); File tempPORfile = null;//from w ww . j a v a 2 s. c o m if (stream == null) { throw new IllegalArgumentException("file == null!"); } byte[] headerByes = new byte[POR_HEADER_SIZE]; if (stream.markSupported()) { stream.mark(1000); } int nbytes = stream.read(headerByes, 0, POR_HEADER_SIZE); //printHexDump(headerByes, "hex dump of the byte-array"); if (nbytes == 0) { throw new IOException("decodeHeader: reading failure"); } else if (nbytes < 491) { // Size test: by defnition, it must have at least // 491-byte header, i.e., the file size less than this threshold // is not a POR file dbgLog.fine("this file is NOT spss-por type"); throw new IllegalArgumentException("file is not spss-por type"); } // rewind the current reading position back to the beginning if (stream.markSupported()) { stream.reset(); } // line-terminating characters are usually one or two by defnition // however, a POR file saved by a genuine SPSS for Windows // had a three-character line terminator, i.e., failed to remove the // original file's one-character terminator when it was opened, and // saved it with the default two-character terminator without // removing original terminators. So we have to expect such a rare // case // // terminator // windows [0D0A]=> [1310] = [CR/LF] // unix [0A] => [10] // mac [0D] => [13] // 3char [0D0D0A]=> [131310] spss for windows rel 15 // // terminating characters should be found at the following // column positions[counting from 0]: // unix case: [0A] : [80], [161], [242], [323], [404], [485] // windows case: [0D0A] : [81], [163], [245], [327], [409], [491] // : [0D0D0A] : [82], [165], [248], [331], [414], [495] // convert b into a ByteBuffer ByteBuffer buff = ByteBuffer.wrap(headerByes); byte[] nlch = new byte[36]; int pos1; int pos2; int pos3; int ucase = 0; int wcase = 0; int mcase = 0; int three = 0; int nolines = 6; int nocols = 80; for (int i = 0; i < nolines; ++i) { int baseBias = nocols * (i + 1); // 1-char case pos1 = baseBias + i; buff.position(pos1); dbgLog.finer("\tposition(1)=" + buff.position()); int j = 6 * i; nlch[j] = buff.get(); if (nlch[j] == 10) { ucase++; } else if (nlch[j] == 13) { mcase++; } // 2-char case pos2 = baseBias + 2 * i; buff.position(pos2); dbgLog.finer("\tposition(2)=" + buff.position()); nlch[j + 1] = buff.get(); nlch[j + 2] = buff.get(); // 3-char case pos3 = baseBias + 3 * i; buff.position(pos3); dbgLog.finer("\tposition(3)=" + buff.position()); nlch[j + 3] = buff.get(); nlch[j + 4] = buff.get(); nlch[j + 5] = buff.get(); dbgLog.finer(i + "-th iteration position =" + nlch[j] + "\t" + nlch[j + 1] + "\t" + nlch[j + 2]); dbgLog.finer(i + "-th iteration position =" + nlch[j + 3] + "\t" + nlch[j + 4] + "\t" + nlch[j + 5]); if ((nlch[j + 3] == 13) && (nlch[j + 4] == 13) && (nlch[j + 5] == 10)) { three++; } else if ((nlch[j + 1] == 13) && (nlch[j + 2] == 10)) { wcase++; } buff.rewind(); } boolean windowsNewLine = true; if (three == nolines) { windowsNewLine = false; // lineTerminator = "0D0D0A" } else if ((ucase == nolines) && (wcase < nolines)) { windowsNewLine = false; // lineTerminator = "0A" } else if ((ucase < nolines) && (wcase == nolines)) { windowsNewLine = true; //lineTerminator = "0D0A" } else if ((mcase == nolines) && (wcase < nolines)) { windowsNewLine = false; //lineTerminator = "0D" } buff.rewind(); int PORmarkPosition = POR_MARK_POSITION_DEFAULT; if (windowsNewLine) { PORmarkPosition = PORmarkPosition + 5; } else if (three == nolines) { PORmarkPosition = PORmarkPosition + 10; } byte[] pormark = new byte[8]; buff.position(PORmarkPosition); buff.get(pormark, 0, 8); String pormarks = new String(pormark); //dbgLog.fine("pormark =>" + pormarks + "<-"); dbgLog.fine( "pormark[hex: 53 50 53 53 50 4F 52 54 == SPSSPORT] =>" + new String(Hex.encodeHex(pormark)) + "<-"); if (pormarks.equals(POR_MARK)) { dbgLog.fine("POR ID toke test: Passed"); init(); dataTable.setOriginalFileFormat(MIME_TYPE); dataTable.setUnf("UNF:6:NOTCALCULATED"); } else { dbgLog.fine("this file is NOT spss-por type"); throw new IllegalArgumentException("decodeHeader: POR ID token was not found"); } // save the POR file without new line characters FileOutputStream fileOutPOR = null; Writer fileWriter = null; // Scanner class can handle three-character line-terminator Scanner porScanner = null; try { tempPORfile = File.createTempFile("tempPORfile.", ".por"); fileOutPOR = new FileOutputStream(tempPORfile); fileWriter = new BufferedWriter(new OutputStreamWriter(fileOutPOR, "utf8")); porScanner = new Scanner(stream); // Because 64-bit and 32-bit machines decode POR's first 40-byte // sequence differently, the first 5 leader lines are skipped from // the new-line-stripped file int lineCounter = 0; while (porScanner.hasNextLine()) { lineCounter++; if (lineCounter <= 5) { String line = porScanner.nextLine(); dbgLog.fine("line=" + lineCounter + ":" + line.length() + ":" + line); } else { fileWriter.write(porScanner.nextLine()); } } } finally { try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException ex) { ex.printStackTrace(); } if (porScanner != null) { porScanner.close(); } } return tempPORfile; }
From source file:com.maxl.java.amikodesk.AMiKoDesk.java
static void sTitle() { List<String> m = new ArrayList<String>(); if (!m_curr_uistate.isComparisonMode()) { med_id.clear();/*from w ww . j av a 2s .co m*/ Pattern p_red = Pattern.compile(".*O]"); Pattern p_green = Pattern.compile(".*G]"); if (med_search.size() < BigCellNumber && m_curr_uistate.isSearchMode()) { for (int i = 0; i < med_search.size(); ++i) { Medication ms = med_search.get(i); String pack_info_str = ""; Scanner pack_str_scanner = new Scanner(ms.getPackInfo()); while (pack_str_scanner.hasNextLine()) { String pack_str_line = pack_str_scanner.nextLine(); Matcher m_red = p_red.matcher(pack_str_line); Matcher m_green = p_green.matcher(pack_str_line); if (m_red.find()) pack_info_str += "<font color=red>" + pack_str_line + "</font><br>"; else if (m_green.find()) pack_info_str += "<font color=green>" + pack_str_line + "</font><br>"; else pack_info_str += "<font color=gray>" + pack_str_line + "</font><br>"; } pack_str_scanner.close(); m.add("<html><b>" + ms.getTitle() + "</b><br><font size=-1>" + pack_info_str + "</font></html>"); med_id.add(ms.getId()); } } else if (!m_curr_uistate.isSearchMode()) { for (int i = 0; i < med_search.size(); ++i) { Medication ms = med_search.get(i); m.add("<html><body style='width: 1024px;'><b>" + ms.getTitle() + "</b></html>"); med_id.add(ms.getId()); } } } else { list_of_articles.clear(); for (int i = 0; i < rose_search.size(); ++i) { Article as = rose_search.get(i); list_of_articles.add(as); m.add("<html><body style='width: 1024px;'><b>" + as.getPackTitle() + "</b><br>" + "<font color=gray size=-1>Lager: " + as.getItemsOnStock() + " (CHF " + as.getCleanExfactoryPrice() + ")" + "</font></html>"); } } m_list_titles.update(m); }
From source file:com.partypoker.poker.engagement.reach.EngagementReachAgent.java
/** * Called when a message download completes. * @param message message parameters./*from w w w . ja v a2 s. c om*/ */ void onMessageDownloaded(Bundle message) { /* * Get all campaigns from storage that matches this DLC identifier (manual push can have several * pushes for same DLC id). */ String id = message.getString(INTENT_EXTRA_ID); if (id == null) return; Scanner scanner = mDB.getScanner(DLC_ID, id); for (ContentValues values : scanner) { /* Parse it */ EngagementReachContent content = null; try { /* Parse and restore state */ content = parseContentFromStorage(values); long localId = content.getLocalId(); mPendingDLCs.remove(localId); boolean mustNotify = !content.isDlcCompleted() && (content.hasNotificationDLC() || content instanceof com.microsoft.azure.engagement.reach.EngagementDataPush); /* Parse downloaded payload as JSON */ String rawPayload = message.getString(INTENT_EXTRA_PAYLOAD); JSONObject payload = new JSONObject(rawPayload); content.setPayload(payload); /* Store it */ ContentValues update = new ContentValues(); update.put(PAYLOAD, rawPayload); mDB.update(localId, update); /* Cache is out of date, update it */ mContentCache.put(localId, content); /* Start content if we were loading it */ if (mState == State.LOADING && localId == mCurrentShownContentId) showContent(content); /* Notify if we were waiting for DLC to generate notification */ else if (mustNotify && mInjectedParams.containsKey("{deviceid}")) notifyContent(content, false); } catch (Exception e) { /* * Delete content and send dropped feedback if possible depending on how much state we could * restore. */ if (content == null) { Long oid = values.getAsLong(OID); if (oid != null) delete(oid); } else content.dropContent(mContext); } } scanner.close(); }
From source file:Creator.WidgetPanel.java
public void readWidgetVars() { groupNamesWidget = new HashMap<>(); String path = "/Creator/textFiles/Default Widget Names.txt"; InputStream loc = this.getClass().getResourceAsStream(path); Scanner scan = new Scanner(loc); String line, groupName = ""; while (scan.hasNextLine()) { line = scan.nextLine();/* w w w .jav a 2s .c o m*/ if (line == null) { // make sure it doesnt break } else if (line.startsWith("`")) { groupName = line.substring(1); if (!groupNamesWidget.containsKey(groupName)) { groupNamesWidget.put(groupName, new ArrayList<>()); } //System.out.println("Grouping name: " + groupName); } else { groupNamesWidget.get(groupName).add(line); } } scan.close(); loadWidgetVarsComboBox(); }