List of usage examples for java.util Scanner Scanner
public Scanner(ReadableByteChannel source)
From source file:IO.java
public static double[] readDoubleVec(File file, int nDim) { Scanner sc;// ww w.j a v a2s . c om double[] wavelength = new double[nDim]; try { sc = new Scanner(file); sc.useDelimiter(",|\\n"); for (int i = 0; i < nDim; i++) { wavelength[i] = Double.parseDouble(sc.next()); //System.out.print(wavelength[i]+"\t"); } } catch (FileNotFoundException e) { System.out.println("Wavelength file not found\n" + e); System.exit(0); } return wavelength; }
From source file:ca.viaware.securefiles.persistence.Serializer.java
public SecurePackage deserialize(ByteArrayInputStream data) { String json = new Scanner(data).useDelimiter("\\Z").next(); //System.out.println(json); JSONObject root = new JSONObject(json); SecurePackage securePackage = new SecurePackage(); JSONArray entries = root.getJSONArray("entries"); for (int i = 0; i < entries.length(); i++) { JSONObject entry = entries.getJSONObject(i); String type = entry.getString("type"); SecureEntry secureEntry = SecureEntry.initialize(type); if (secureEntry != null) { secureEntry.setTitle(entry.getString("title")); if (entry.has("payload")) { secureEntry.load(entry.getString("payload")); }/*from w w w .j a va2s .com*/ securePackage.addEntry(secureEntry); } } return securePackage; }
From source file:games.livestreams.providers.Twitch.java
@Override public String[] getStreams(String tag) { final ArrayList<String> streams = new ArrayList<String>(); String apiUrl = String.format(ExtensionObject.Configuration.get("twitch.link"), Integer.parseInt(ExtensionObject.Configuration.get("streams.limit")), tag); try {/* w w w.jav a2 s. c o m*/ // apiUrl = URLEncoder.encode(apiUrl, "UTF-8"); URL url = new URL(apiUrl); Scanner scan = new Scanner(url.openStream()); String jsonAnswer = ""; while (scan.hasNext()) jsonAnswer += scan.nextLine(); scan.close(); JSONObject jsonObject = new JSONObject(jsonAnswer); JSONArray jsonArray = jsonObject.getJSONArray("streams"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject streamObject = jsonArray.getJSONObject(i); String streamName = streamObject.getJSONObject("channel").getString("display_name"); String streamStatus = "online"; String streamUrl = streamObject.getJSONObject("channel").getString("url"); String streamViewers = streamObject.getString("viewers"); streamName = IrcMessageTextModifier.makeBold(streamName); streamViewers = IrcMessageTextModifier.makeColoured(IrcMessageTextModifier.makeBold(streamViewers), IrcTextColor.Brown); String realStatus = streamObject.getJSONObject("channel").getString("status"); if (realStatus != null && !realStatus.trim().isEmpty()) { streamStatus = realStatus; } String formattedStreamInfoOutput = String.format("[%s] (%s) %s (%s viewers)", streamName, streamStatus, streamUrl, streamViewers); streams.add(formattedStreamInfoOutput); } } catch (Exception e) { System.out.println(e.getMessage()); } if (!streams.isEmpty()) { String[] streamsArray = new String[] {}; return streams.toArray(streamsArray); } else { throw new ProviderError(String.format("No streams found on \"%s\" service with tag \"%s\"", this.getProviderName(), tag)); } }
From source file:CommandLineInterpreter.java
/** * * * @param file/*from ww w. j a va 2s . co m*/ * @param guiAlert * @return */ public static boolean checkResources(final File file, final boolean guiAlert) { Scanner input = null; String message = null; try { input = new Scanner(file); while (input.hasNextLine()) { String currentFilePath = input.nextLine().trim(); if (!currentFilePath.isEmpty()) { File currentFile = new File(currentFilePath); if (!currentFile.exists() || !currentFile.canRead() || !currentFile.canWrite()) { message = "Can not read/write resource file:\n\"" + currentFile.getAbsolutePath() + "\""; alert(message, guiAlert); return false; } } } } catch (Exception e) { // TODO: logging e.printStackTrace(); } finally { if (input != null) { input.close(); } } return true; }
From source file:csns.importer.parser.MFTScoreParser.java
public void parse(MFTScoreImporter importer) { Department department = importer.getDepartment(); Date date = importer.getDate(); Scanner scanner = new Scanner(importer.getText()); scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n"); while (scanner.hasNext()) { // last name String lastName = scanner.next(); while (!lastName.endsWith(",")) lastName += " " + scanner.next(); lastName = lastName.substring(0, lastName.length() - 1); // first name String firstName = scanner.next(); // score/*from w w w . j a v a2s . c om*/ Stack<String> stack = new Stack<String>(); String s = scanner.next(); while (!isScore(s)) { stack.push(s); s = scanner.next(); } int value = Integer.parseInt(s); // authorization code stack.pop(); // cin String cin = null; if (!stack.empty() && isCin(stack.peek())) cin = stack.pop(); // user User user = null; if (cin != null) user = userDao.getUserByCin(cin); else { List<User> users = userDao.getUsers(lastName, firstName); if (users.size() == 1) user = users.get(0); } if (user != null) { MFTScore score = mftScoreDao.getScore(department, date, user); if (score == null) { score = new MFTScore(); score.setDepartment(department); score.setDate(date); score.setUser(user); } else { logger.info(user.getId() + ": " + score.getValue() + " => " + value); } score.setValue(value); importer.getScores().add(score); } else { User failedUser = new User(); failedUser.setLastName(lastName); failedUser.setFirstName(firstName); failedUser.setCin(cin); importer.getFailedUsers().add(failedUser); } logger.debug(lastName + "," + firstName + "," + cin + "," + value); } scanner.close(); }
From source file:jfractus.app.Main.java
private static void parseSize(String sizeStr, Dimension dim) throws ArgumentParseException, BadValueOfArgumentException { Scanner scanner = new Scanner(sizeStr); scanner.useLocale(Locale.ENGLISH); scanner.useDelimiter("x"); int outWidth = 0, outHeight = 0; try {/* ww w .j a va 2 s . co m*/ outWidth = scanner.nextInt(); outHeight = scanner.nextInt(); if (outWidth < 0 || outHeight < 0) throw new BadValueOfArgumentException("Bad value of argument"); } catch (InputMismatchException e) { throw new ArgumentParseException("Command line parse exception"); } catch (NoSuchElementException e) { throw new ArgumentParseException("Command line parse exception"); } if (scanner.hasNext()) throw new ArgumentParseException("Command line parse exception"); dim.setSize(outWidth, outHeight); }
From source file:org.zrgs.spring.statemachine.CommonConfiguration.java
@Bean public String stateChartModel() throws IOException { ClassPathResource model = new ClassPathResource("statechartmodel.txt"); InputStream inputStream = model.getInputStream(); Scanner scanner = new Scanner(inputStream); String content = scanner.useDelimiter("\\Z").next(); scanner.close();//from w ww .jav a2 s. co m return content; }
From source file:com.l2jfree.gameserver.datatables.ExtractableSkillsData.java
private ExtractableSkillsData() { _items.clear();// www .ja va 2 s . c om Scanner s; try { s = new Scanner(new File(Config.DATAPACK_ROOT, "data/extractable_skills.csv")); } catch (Exception e) { _log.warn("Extractable items data: Can not find '" + Config.DATAPACK_ROOT + "data/extractable_skills.csv'"); return; } int lineCount = 0; while (s.hasNextLine()) { lineCount++; String line = s.nextLine().trim(); if (line.startsWith("#")) continue; else if (line.isEmpty()) continue; String[] lineSplit = line.split(";"); boolean ok = true; int skillID = 0; int skillLevel = 0; try { skillID = Integer.parseInt(lineSplit[0]); skillLevel = Integer.parseInt(lineSplit[1]); } catch (Exception e) { _log.warn("Extractable skills data: Error in line " + lineCount + " -> invalid item id or wrong seperator after skill id!"); _log.warn(" " + line); ok = false; } L2Skill skill = SkillTable.getInstance().getInfo(skillID, skillLevel); if (skill == null) { _log.warn("Extractable skills data: Error in line " + lineCount + " -> skill is null!"); _log.warn(" " + line); ok = false; } if (!ok) continue; FastList<L2ExtractableProductItem> product_temp = new FastList<L2ExtractableProductItem>(); for (int i = 1; i < lineSplit.length - 1; i++) { ok = true; String[] lineSplit2 = lineSplit[i + 1].split(","); if (lineSplit2.length < 3) { _log.warn("Extractable items data: Error in line " + lineCount + " -> wrong seperator!"); _log.warn(" " + line); ok = false; } if (!ok) continue; int[] production = null; int[] amount = null; int chance = 0; try { int k = 0; production = new int[(lineSplit2.length - 1) / 2]; amount = new int[(lineSplit2.length - 1) / 2]; for (int j = 0; j < lineSplit2.length - 1; j++) { production[k] = Integer.parseInt(lineSplit2[j]); amount[k] = Integer.parseInt(lineSplit2[j += 1]); k++; } chance = Integer.parseInt(lineSplit2[lineSplit2.length - 1]); } catch (Exception e) { _log.warn("Extractable skills data: Error in line " + lineCount + " -> incomplete/invalid production data or wrong seperator!"); _log.warn(" " + line); ok = false; } if (!ok) continue; L2ExtractableProductItem product = new L2ExtractableProductItem(production, amount, chance); product_temp.add(product); } int fullChances = 0; for (L2ExtractableProductItem Pi : product_temp) fullChances += Pi.getChance(); if (fullChances > 100) { _log.warn("Extractable skills data: Error in line " + lineCount + " -> all chances together are more then 100!"); _log.warn(" " + line); continue; } int hash = SkillTable.getSkillUID(skill); L2ExtractableSkill product = new L2ExtractableSkill(hash, product_temp); _items.put(hash, product); } s.close(); _log.info("Extractable items data: Loaded " + _items.size() + " extractable skills!"); }
From source file:com.starit.diamond.server.utils.SystemConfig.java
public static void system_pause() { System.out.println("press ANY KEY to QUIT."); Scanner scanner = new Scanner(System.in); scanner.next();/*from w w w . j a va2 s . c o m*/ }
From source file:example.store.StoreInitializer.java
/** * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to * persisted./*from w w w . jav a2 s .co m*/ * * @return * @throws Exception */ public static List<Store> readStores() throws Exception { ClassPathResource resource = new ClassPathResource("starbucks.csv"); Scanner scanner = new Scanner(resource.getInputStream()); String line = scanner.nextLine(); scanner.close(); FlatFileItemReader<Store> itemReader = new FlatFileItemReader<Store>(); itemReader.setResource(resource); // DelimitedLineTokenizer defaults to comma as its delimiter DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); tokenizer.setNames(line.split(",")); tokenizer.setStrict(false); DefaultLineMapper<Store> lineMapper = new DefaultLineMapper<Store>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(StoreFieldSetMapper.INSTANCE); itemReader.setLineMapper(lineMapper); itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy()); itemReader.setLinesToSkip(1); itemReader.open(new ExecutionContext()); List<Store> stores = new ArrayList<>(); Store store = null; do { store = itemReader.read(); if (store != null) { stores.add(store); } } while (store != null); return stores; }