List of usage examples for java.util Scanner close
public void close()
From source file:com.bluexml.tools.miscellaneous.Translate.java
/** * @param args/*from w w w . j a v a 2s .c om*/ */ public static void main(String[] args) { System.out.println("Translate.main() 1"); Console console = System.console(); System.out.println("give path to folder that contains properties files"); Scanner scanIn = new Scanner(System.in); try { // TODO Auto-generated method stub String sWhatever; System.out.println("Translate.main() 2"); sWhatever = scanIn.nextLine(); System.out.println("Translate.main() 3"); System.out.println(sWhatever); File inDir = new File(sWhatever); FilenameFilter filter = new FilenameFilter() { public boolean accept(File arg0, String arg1) { return arg1.endsWith("properties"); } }; File[] listFiles = inDir.listFiles(filter); for (File file : listFiles) { prapareFileToTranslate(file, inDir); } System.out.println("please translate text files and press enter"); String readLine = scanIn.nextLine(); System.out.println("Translate.main() 4"); for (File file : listFiles) { File values = new File(file.getParentFile(), file.getName() + ".txt"); writeBackValues(values, file); values.delete(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { scanIn.close(); } }
From source file:Graph_with_jframe_and_arduino.java
public static void main(String[] args) { // create and configure the window JFrame window = new JFrame(); window.setTitle("Sensor Graph GUI"); window.setSize(600, 400);//from ww w.j av a 2 s. c o m window.setLayout(new BorderLayout()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a drop-down box and connect button, then place them at the top of the window JComboBox<String> portList_combobox = new JComboBox<String>(); Dimension d = new Dimension(300, 100); portList_combobox.setSize(d); JButton connectButton = new JButton("Connect"); JPanel topPanel = new JPanel(); topPanel.add(portList_combobox); topPanel.add(connectButton); window.add(topPanel, BorderLayout.NORTH); //pause button JButton Pause_btn = new JButton("Start"); // populate the drop-down box SerialPort[] portNames; portNames = SerialPort.getCommPorts(); //check for new port available Thread thread_port = new Thread() { @Override public void run() { while (true) { SerialPort[] sp = SerialPort.getCommPorts(); if (sp.length > 0) { for (SerialPort sp_name : sp) { int l = portList_combobox.getItemCount(), i; for (i = 0; i < l; i++) { //check port name already exist or not if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) { break; } } if (i == l) { portList_combobox.addItem(sp_name.getSystemPortName()); } } } else { portList_combobox.removeAllItems(); } portList_combobox.repaint(); } } }; thread_port.start(); for (SerialPort sp_name : portNames) portList_combobox.addItem(sp_name.getSystemPortName()); //for(int i = 0; i < portNames.length; i++) // portList.addItem(portNames[i].getSystemPortName()); // create the line graph XYSeries series = new XYSeries("line 1"); XYSeries series2 = new XYSeries("line 2"); XYSeries series3 = new XYSeries("line 3"); XYSeries series4 = new XYSeries("line 4"); for (int i = 0; i < 100; i++) { series.add(x, 0); series2.add(x, 0); series3.add(x, 0); series4.add(x, 10); x++; } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); dataset.addSeries(series2); XYSeriesCollection dataset2 = new XYSeriesCollection(); dataset2.addSeries(series3); dataset2.addSeries(series4); //create jfree chart JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading", dataset); JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2", dataset2); //color render for chart 1 XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(); r1.setSeriesPaint(0, Color.RED); r1.setSeriesPaint(1, Color.GREEN); r1.setSeriesShapesVisible(0, false); r1.setSeriesShapesVisible(1, false); XYPlot plot = chart.getXYPlot(); plot.setRenderer(0, r1); plot.setRenderer(1, r1); plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinePaint(Color.DARK_GRAY); plot.setRangeGridlinePaint(Color.blue); //color render for chart 2 XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer(); r2.setSeriesPaint(0, Color.BLUE); r2.setSeriesPaint(1, Color.ORANGE); r2.setSeriesShapesVisible(0, false); r2.setSeriesShapesVisible(1, false); XYPlot plot2 = chart2.getXYPlot(); plot2.setRenderer(0, r2); plot2.setRenderer(1, r2); ChartPanel cp = new ChartPanel(chart); ChartPanel cp2 = new ChartPanel(chart2); //multiple graph container JPanel graph_container = new JPanel(); graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS)); graph_container.add(cp); graph_container.add(cp2); //add chart panel in main window window.add(graph_container, BorderLayout.CENTER); //window.add(cp2, BorderLayout.WEST); window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE); Pause_btn.setEnabled(false); //pause btn action Pause_btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (Pause_btn.getText().equalsIgnoreCase("Pause")) { if (chosenPort.isOpen()) { try { Output.write(0); } catch (IOException ex) { Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null, ex); } } Pause_btn.setText("Start"); } else { if (chosenPort.isOpen()) { try { Output.write(1); } catch (IOException ex) { Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null, ex); } } Pause_btn.setText("Pause"); } throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // configure the connect button and use another thread to listen for data connectButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (connectButton.getText().equals("Connect")) { // attempt to connect to the serial port chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString()); chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0); if (chosenPort.openPort()) { Output = chosenPort.getOutputStream(); connectButton.setText("Disconnect"); Pause_btn.setEnabled(true); portList_combobox.setEnabled(false); } // create a new thread that listens for incoming text and populates the graph Thread thread = new Thread() { @Override public void run() { Scanner scanner = new Scanner(chosenPort.getInputStream()); while (scanner.hasNextLine()) { try { String line = scanner.nextLine(); int number = Integer.parseInt(line); series.add(x, number); series2.add(x, number / 2); series3.add(x, number / 1.5); series4.add(x, number / 5); if (x > 100) { series.remove(0); series2.remove(0); series3.remove(0); series4.remove(0); } x++; window.repaint(); } catch (Exception e) { } } scanner.close(); } }; thread.start(); } else { // disconnect from the serial port chosenPort.closePort(); portList_combobox.setEnabled(true); Pause_btn.setEnabled(false); connectButton.setText("Connect"); } } }); // show the window window.setVisible(true); }
From source file:com.precioustech.fxtrading.oanda.restapi.marketdata.historic.HistoricMarketDataOnDemandDemo.java
public static void main(String[] args) throws Exception { usage(args);//from w w w.j ava 2s .c om final String url = args[0]; final String accessToken = args[1]; HistoricMarketDataProvider<String> historicMarketDataProvider = new OandaHistoricMarketDataProvider(url, accessToken); Scanner scanner = new Scanner(System.in); scanner.useDelimiter(System.getProperty("line.separator")); System.out.print("Instrument" + TradingConstants.COLON); String ccyPair = scanner.next(); TradeableInstrument<String> instrument = new TradeableInstrument<>(ccyPair.toUpperCase()); System.out.print( "Granularity" + ArrayUtils.toString(CandleStickGranularity.values()) + TradingConstants.COLON); CandleStickGranularity granularity = CandleStickGranularity.valueOf(scanner.next().toUpperCase()); System.out.print("Time Range Candles(t) or Last N Candles(n)?:"); String choice = scanner.next(); List<CandleStick<String>> candles = null; if ("t".equalsIgnoreCase(choice)) { System.out.print("Start Time(" + datefmtLabel + ")" + TradingConstants.COLON); String startStr = scanner.next(); Date startDt = sdf.parse(startStr); System.out.print(" End Time(" + datefmtLabel + ")" + TradingConstants.COLON); String endStr = scanner.next(); Date endDt = sdf.parse(endStr); candles = historicMarketDataProvider.getCandleSticks(instrument, granularity, new DateTime(startDt.getTime()), new DateTime(endDt.getTime())); } else { System.out.print("Last how many candles?" + TradingConstants.COLON); int n = scanner.nextInt(); candles = historicMarketDataProvider.getCandleSticks(instrument, granularity, n); } System.out.println(center("Time", timeColLen) + center("Open", priceColLen) + center("Close", priceColLen) + center("High", priceColLen) + center("Low", priceColLen)); System.out.println(repeat("=", timeColLen + priceColLen * 4)); for (CandleStick<String> candle : candles) { System.out.println(center(sdf.format(candle.getEventDate().toDate()), timeColLen) + formatPrice(candle.getOpenPrice()) + formatPrice(candle.getClosePrice()) + formatPrice(candle.getHighPrice()) + formatPrice(candle.getLowPrice())); } scanner.close(); }
From source file:gis.proj.drivers.Snyder.java
public static void main(String... args) { Snyder snyder = new Snyder(); JCommander jc = new JCommander(snyder); try {// w ww . j av a2 s. c o m jc.parse(args); } catch (Exception e) { jc.usage(); System.exit(-10); } String fFormat = "(forward) X: %18.9f, Y: %18.9f%n"; String iFormat = "(inverse) Lon: %18.9f, Lat: %18.9f%n%n"; double[][] xy, ll = null; java.util.regex.Pattern pq = java.util.regex.Pattern.compile("quit", java.util.regex.Pattern.CASE_INSENSITIVE); java.util.Scanner s = new java.util.Scanner(System.in); Projection proj = null; printLicenseInformation("Snyder"); try { System.out.println("Loading projection: " + snyder.projStr); Class<?> cls = Class.forName(snyder.projStr); proj = (Projection) cls.newInstance(); } catch (Exception ex) { ex.printStackTrace(); } double lon = 0.0, lat = 0.0, x = 0.0, y = 0.0; Datum d = new Datum(); Ellipsoid e = EllipsoidFactory.getInstance().getEllipsoid(snyder.ellpStr); System.out.println("\nEllipsoid: " + snyder.ellpStr + ", " + e.getName() + ", " + e.getId() + ", " + e.getDescription()); for (String prop : e.getPropertyNames()) { System.out.println("\t" + prop + "\t" + e.getProperty(prop)); } String cmdEntryLine = (snyder.inverse ? "\nx y " : "\nlon lat") + ": "; for (String dProp : proj.getDatumProperties()) { d.setUserOverrideProperty(dProp, 0.0); } System.out.print(cmdEntryLine); while (s.hasNext(pq) == false) { if (snyder.inverse == false) { lon = parseDatumVal(s.next()); lat = parseDatumVal(s.next()); } else { x = parseDatumVal(s.next()); y = parseDatumVal(s.next()); } for (String dp : d.getPropertyNames()) { System.out.print(dp + ": "); d.setUserOverrideProperty(dp, parseDatumVal(s.next())); } System.out.println(); if (snyder.inverse == false) { xy = proj.forward(new double[] { lon }, new double[] { lat }, e, d); System.out.printf(fFormat, xy[0][0], xy[1][0]); ll = proj.inverse(new double[] { xy[0][0] }, new double[] { xy[1][0] }, e, d); System.out.printf(iFormat, StrictMath.toDegrees(ll[0][0]), StrictMath.toDegrees(ll[1][0])); } else { ll = proj.inverse(new double[] { x }, new double[] { y }, e, d); System.out.printf(iFormat, StrictMath.toDegrees(ll[0][0]), StrictMath.toDegrees(ll[1][0])); xy = proj.forward(new double[] { ll[0][0] }, new double[] { ll[1][0] }, e, d); System.out.printf(fFormat, xy[0][0], xy[1][0]); } System.out.print(cmdEntryLine); } s.close(); }
From source file:com.git.ifly6.components.Census.java
public static void main(String[] args) { Scanner scan = new Scanner(System.in); try {/*from w ww. j a v a 2s. co m*/ region = new NSRegion(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("Please input the name of your region: \t"); region = new NSRegion(scan.nextLine()); } try { HashMap<String, Integer> endoMap = new HashMap<String, Integer>(); String[] waMembers = region.getWAMembers(); int[] valueCount = new int[waMembers.length]; System.out.println( "[INFO] This census will take: " + time((int) Math.round(waitTime * waMembers.length))); for (int i = 0; i < waMembers.length; i++) { NSNation nation = new NSNation(waMembers[i]); valueCount[i] = nation.getEndoCount(); endoMap.put(waMembers[i], new Integer(valueCount[i])); System.out.println("[LOG] Fetched information for: " + waMembers[i] + ", " + (i + 1) + " of " + waMembers.length); } TreeMap<String, Integer> sortedMap = sortByValue(endoMap); int current = 0; int previous = sortedMap.firstEntry().getValue(); System.out.printf("%-35s %12s %12s%n", "Nations", "Endorsements", "Difference"); System.out.println("-------------------------------------------------------------"); for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) { String nationName = StringUtils.capitalize(entry.getKey().replace('_', ' ')); current = entry.getValue(); if ((previous - current) != 0) { System.out.printf("%-35s %12s %12s%n", nationName, entry.getValue(), (previous - current)); } else { System.out.printf("%-35s %12s %12s%n", nationName, entry.getValue(), "-"); } previous = entry.getValue(); } System.out.println("-------------------------------------------------------------"); System.out.printf("%-35s %12s %12s%n", "Delegate", "Endorsements", "Proportion"); System.out.printf("%-35s %12s %12s%n", StringUtils.capitalize(sortedMap.firstEntry().getKey().replace('_', ' ')), sortedMap.firstEntry().getValue(), (double) (sortedMap.firstEntry().getValue() / waMembers.length)); } catch (IOException e) { printError("Failed to fetch WA members or get endorsements in this region. " + "Check your internet connection or the state of the API."); } scan.close(); }
From source file:com.vmware.fdmsecprotomgmt.PasswdEncrypter.java
/** * Entry point into this Class/*from w w w . ja va 2 s. c o m*/ */ public static void main(String[] args) { boolean validVals = false; String secretKey = ""; String esxi_pwd = ""; System.out.println("This Utility program would help you to ENCRYPT password with a given secretKey"); Scanner in = new Scanner(System.in); System.out.print("Enter ESXi host password:"); esxi_pwd = in.nextLine().trim(); if (esxi_pwd.equals("")) { System.err.println("Invalid password entry, please try again ..."); } else { System.out.println( "Enter SecretKey to be used for encrypting ESXi Password. MUST NOT exceed 16 characters," + "and should be different from ESXi password; for better security"); secretKey = in.nextLine().trim(); if (secretKey.equals("")) { System.err.println("Invalid SecretKey entry, please try again ..."); } else if (secretKey.length() > STD_KEYSIZE) { System.err.println("SecretKey can NOT exceed 16 characters. Please try again"); } else if (secretKey.length() < STD_KEYSIZE) { int remainingChars = STD_KEYSIZE - secretKey.length(); while (remainingChars > 0) { secretKey = secretKey + PADDING_ARRAY[remainingChars]; --remainingChars; } } if (secretKey.length() == STD_KEYSIZE) { validVals = true; } } // Go for encrypting the password with provided SecretKey if (validVals) { String encryptedStr = encrypt(secretKey, esxi_pwd); if ((!encryptedStr.equals(""))) { // Validate that on decrypt, you would receive the same password String decryptedStr = decrypt(secretKey, encryptedStr); if (!decryptedStr.equals("")) { if (decryptedStr.equals(esxi_pwd)) { System.out.println("Successfully encrypted the password"); System.out.println("----------------------------------------------------------------"); System.out.println("ESXi Password: " + esxi_pwd); System.out.println("Your Secret key: " + secretKey); System.out.println("Encrypted String for the password: " + encryptedStr); System.out.println("[TESTED] Decrypted string: " + decryptedStr); System.out.println("----------------------------------------------------------------"); System.out.println("**** NOTE ****"); System.out.println( "Please remember the secretkey, which is later needed when running TLS-Configuration script"); } else { System.err.println("Failed to match the password with decrypted string"); } } else { System.err.println("Failed to decrypt the encrypted string"); } } else { System.err.println("Failed to encrypt the provided password"); } } // close the scanner in.close(); }
From source file:id3Crawler.java
public static void main(String[] args) throws IOException { //Input for the directory to be searched. System.out.println("Please enter a directory: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); //Start a timer to calculate runtime startTime = System.currentTimeMillis(); System.out.println("Starting scan..."); //Files for output PrintWriter pw1 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Song.txt")); PrintWriter pw2 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Artist.txt")); PrintWriter pw3 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Album.txt")); PrintWriter pw4 = new PrintWriter( new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/PerformedBy.txt")); PrintWriter pw5 = new PrintWriter( new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/TrackOf.txt")); PrintWriter pw6 = new PrintWriter( new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/CreatedBy.txt")); //This is used for creating IDs for artists, songs, albums. int idCounter = 0; //This is used to prevent duplicate artists String previousArtist = " "; String currentArtist;//from w ww .jav a 2s . co m int artistID = 0; //This is used to prevent duplicate albums String previousAlbum = " "; String currentAlbum; int albumID = 0; //This array holds valid extensions to iterate through String[] extensions = new String[] { "mp3" }; //iterate through all files in a directory Iterator<File> it = FileUtils.iterateFiles(new File(input), extensions, true); while (it.hasNext()) { //open the next file File file = it.next(); //instantiate an mp3file object with the opened file MP3 song = GetMP3(file); //pass the song through SongInfo and return the required information SongInfo info = new SongInfo(song); //This is used to prevent duplicate artists/albums currentArtist = info.getArtistInfo(); currentAlbum = info.getAlbumInfo(); //Append the song information to the end of a text file pw1.println(idCounter + "\t" + info.getTitleInfo()); //This prevents duplicates of artists if (!(currentArtist.equals(previousArtist))) { pw2.println(idCounter + "\t" + info.getArtistInfo()); previousArtist = currentArtist; artistID = idCounter; } //This prevents duplicates of albums if (!(currentAlbum.equals(previousAlbum))) { pw3.println(idCounter + "\t" + info.getAlbumInfo()); previousAlbum = currentAlbum; albumID = idCounter; //This formats the IDs for a "CreatedBy" relationship table pw6.println(artistID + "\t" + albumID); } //This formats the IDs for a "PerformedBy" relationship table pw4.println(idCounter + "\t" + artistID); //This formats the IDs for a "TrackOf" relationship table pw5.println(idCounter + "\t" + albumID); idCounter++; songCounter++; } scanner.close(); pw1.close(); pw2.close(); pw3.close(); pw4.close(); pw5.close(); pw6.close(); System.out.println("Scan took " + ((System.currentTimeMillis() - startTime) / 1000.0) + " seconds to scan " + songCounter + " items!"); }
From source file:gash.router.app.DemoApp.java
/** * sample application (client) use of our messaging service * * @param args/*from w w w.j a v a 2s . c o m*/ */ public static void main(String[] args) { if (args.length == 0) { System.out.println("usage: <ip address> <port no>"); System.exit(1); } String ipAddress = args[0]; int port = Integer.parseInt(args[1]); Scanner s = new Scanner(System.in); boolean isExit = false; try { MessageClient mc = new MessageClient(ipAddress, port); DemoApp da = new DemoApp(mc); int choice = 0; while (true) { System.out.println( "Enter your option \n1. WRITE a file. \n2. READ a file. \n3. Update a File. \n4. Delete a File\n 5 Ping(Global)\n 6 Exit"); choice = s.nextInt(); switch (choice) { case 1: { System.out.println("Enter the full pathname of the file to be written "); String currFileName = s.next(); File file = new File(currFileName); if (file.exists()) { ArrayList<ByteString> chunkedFile = da.divideFileChunks(file); String name = file.getName(); int i = 0; String requestId = SupportMessageGenerator.generateRequestID(); for (ByteString string : chunkedFile) { mc.saveFile(name, string, chunkedFile.size(), i++, requestId); } } else { throw new FileNotFoundException("File does not exist in this path "); } } break; case 2: { System.out.println("Enter the file name to be read : "); String currFileName = s.next(); da.sendReadTasks(currFileName); //Thread.sleep(1000 * 100); } break; case 3: { System.out.println("Enter the full pathname of the file to be updated"); String currFileName = s.next(); File file = new File(currFileName); if (file.exists()) { ArrayList<ByteString> chunkedFile = da.divideFileChunks(file); String name = file.getName(); int i = 0; String requestId = SupportMessageGenerator.generateRequestID(); for (ByteString string : chunkedFile) { mc.updateFile(name, string, chunkedFile.size(), i++, requestId); } //Thread.sleep(10 * 1000); } else { throw new FileNotFoundException("File does not exist in this path "); } } break; case 4: System.out.println("Enter the file name to be deleted : "); String currFileName = s.next(); mc.deleteFile(currFileName); //Thread.sleep(1000 * 100); break; case 5: da.ping(1); break; case 6: isExit = true; break; default: break; } if (isExit) break; } } catch (Exception e) { e.printStackTrace(); } finally { CommConnection.getInstance().release(); if (s != null) s.close(); } }
From source file:Main.java
public static void close(final Scanner scanner) { if (scanner != null) { scanner.close(); }/*from w w w.ja va 2 s. co m*/ }
From source file:Main.java
static Long toNumeric(String ip) { Scanner sc = new Scanner(ip).useDelimiter("\\."); Long l = (sc.nextLong() << 24) + (sc.nextLong() << 16) + (sc.nextLong() << 8) + (sc.nextLong()); sc.close(); return l;//from www . j a v a 2 s .c o m }