public HashMap<Integer, Integer> readinput(String fname) throws FileNotFoundException { HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); FileReader fr = new FileReader(fname); Scanner sc =new Scanner(new BufferedReader(fr)); int amt=0; while(sc.hasNext()) { int act=Integer.parseInt(sc.useDelimiter(" ").next().trim()); String status=sc.useDelimiter(" ").next(); amt=Integer.parseInt(sc.useDelimiter("\n").next().trim()); Integer check_key=map.get(act); if(check_key!=null){ if(status.equalsIgnoreCase("Deposit")) map.put(act,check_key+amt); else map.put(act, check_key-amt); } else { check_key=0; if(status.equalsIgnoreCase("Deposit")) map.put(act,check_key+amt); else map.put(act, check_key-amt); } } System.out.println(map); return map; }
private static UnivariatePalette readPalette(Scanner scan) { String line = scan.nextLine(); Scanner lineScan = new Scanner(line); lineScan.useDelimiter(","); String name = lineScan.next(); int maxLength = lineScan.nextInt(); SequenceType type = findSequenceType(lineScan.next()); HashMap<Integer, Color[]> colorMap = new HashMap<Integer, Color[]>(); Color[] colors = new Color[maxLength]; for (int i = 0; i < maxLength; i++) { if (i > 0) { line = scan.nextLine(); lineScan = new Scanner(line); lineScan.useDelimiter(","); lineScan.next(); lineScan.next(); } String indexString = lineScan.next(); int index = Integer.valueOf(indexString); assert (i == index - 1); lineScan.next(); // skip letter int r = lineScan.nextInt(); int g = lineScan.nextInt(); String bString = lineScan.next(); // logger.info("bString = " + bString); int b = Integer.valueOf(bString.trim()); Color col = new Color(r, g, b); colors[i] = col; } colorMap.put(maxLength, colors); UnivariatePalette pal = new UnivariatePalette(name, type, colorMap, maxLength); return pal; }
/** * Reads and returns the next character. * * @return the next character */ public static char readChar() { scanner.useDelimiter(EMPTY_PATTERN); String ch = scanner.next(); assert ch.length() == 1 : "Internal (Std)In.readChar() error!" + " Please contact the authors."; scanner.useDelimiter(WHITESPACE_PATTERN); return ch.charAt(0); }
/** Read and return the remainder of the input as a string. */ public static String readAll() { if (!scanner.hasNextLine()) return ""; String result = scanner.useDelimiter(EVERYTHING_PATTERN).next(); // not that important to reset delimeter, since now scanner is empty scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway return result; }
private String nextWithAltDelimiter(Scanner source, Pattern altDelimiter) { Pattern delimiter = source.delimiter(); try { source.useDelimiter(altDelimiter); return source.next(); } finally { source.useDelimiter(delimiter); } }
public int getVolumesForSubject(String filename, double x[]) { BufferedReader input; Scanner sc; int i; int err = 0; String a = " "; for (i = 0; i < 16; i++) x[i] = -1; // Load ICV and BrainSeg data try { input = new BufferedReader( new FileReader(subjectsDir + "/" + filename + "/Process_FSL/size_FSL.csv")); sc = new Scanner(input.readLine()); // "000000022453,1347750,0.825819");// sc.useDelimiter(","); // System.out.println("dans try: passe à la seconde ligne: "+sc.nextFloat()); sc.next(); // skip subject ID column for (i = 0; i < 2; i++) { a = sc.next(); x[i] = Double.valueOf(a.trim()).doubleValue(); } sc.close(); } catch (IOException e) { err = 1; return err; } catch (InputMismatchException e) { System.out.println("erreur InputMismatchException " + e.getMessage()); err = 1; return err; } // System.out.println("subectsDir"+subjectsDir+" filename: "+filename); // Load Subcortical data try { input = new BufferedReader( new FileReader(subjectsDir + "/" + filename + "/Process_FSL/LandRvolumes.csv")); input.readLine(); // skip header row sc = new Scanner(input.readLine()); sc.useDelimiter(","); sc.next(); // skip subject ID column for (i = 2; i < 16; i++) { a = sc.next(); x[i] = Double.valueOf(a.trim()).doubleValue(); } sc.close(); } catch (IOException e) { err = 1; return err; } catch (InputMismatchException e) { err = 1; return err; } return err; }
protected String nextDelimiter(Scanner source) { Pattern delimiter = source.delimiter(); try { source.useDelimiter(AFTER_DELIMITER); if (source.hasNext()) { return source.next(); } else { return null; } } finally { source.useDelimiter(delimiter); } }
// control thread that allows continuous update of displayArea public void run() { // myMark = input.nextLine(); // get player's mark (X or O) String xmlResponse = input.useDelimiter("\\z").next().trim(); // get // player's // mark // (X or // O) System.out.println("*************************************************"); System.out.println("Method run of client"); System.out.println("*************************************************"); System.out.println(xmlResponse + "\n"); // Parse Response String from Server XML to Object XStream xt = new XStream(); xt.alias("ticTacToe", XMLMoveResponse.class); XMLMoveResponse response = (XMLMoveResponse) xt.fromXML(xmlResponse); myMark = response.getMark().getMark(); SwingUtilities.invokeLater( new Runnable() { public void run() { // display player's mark idField.setText("You are player \"" + myMark + "\""); } // end method run } // end anonymous inner class ); // end call to SwingUtilities.invokeLater myTurn = (myMark.equals(X_MARK)); // determine if client's turn // receive messages sent to client and output them while (true) { // teste try { // Fix String Buffer (1024) clas Scanner input = new Scanner(connection.getInputStream()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // if (input.hasNextLine()) // processMessage(input.nextLine()); processMessage(input.useDelimiter("\\z").next().trim()); } // end while } // end method run
public static String convertStreamToString(InputStream is) { java.util.Scanner s = new java.util.Scanner(is); s.useDelimiter("\\A"); String value = s.hasNext() ? s.next() : ""; s.close(); return value; }
// NOTE: Execute this initialization PRIOR to any other. public static void initializeParameters(String parameterFile) { try { // Open the file to be read InputStream fstream = PortParameter.stream(parameterFile); // Create an object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); int nLine = 0; // Line number String line; while ((line = buff.readLine()) != null) { nLine++; // Increment line number if (line.length() > 0) { // Ignore empty lines if (line.charAt(0) != '#') { // Ignore comments Scanner scanner = new Scanner(line); scanner.useDelimiter("="); // Get option name and value. If not valid, exit program! String optionName = scanner.next().trim(); validateOptionName(line, optionName, nLine); String optionValue = scanner.next().trim(); validateOptionValue(optionName, optionValue, nLine); } } } in.close(); } // Catch open file error. catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
/** * Submit query via the submit_plan tool * * @param submitPlanCommand command of submit_plan * @param queryFileName name of file containing input query * @param outputFileName name of file containing query results * @param queryType type of query: sql, logical or physical * @throws Exception */ public void submitQueriesSubmitPlan( String submitPlanCommand, String queryFileName, String outputFileName, String queryType, long timeout) throws Exception { String command = submitPlanCommand + " -f " + queryFileName + " --format tsv -t " + queryType + " -z " + Utils.getDrillTestProperties().get("ZOOKEEPERS"); LOG.debug("Executing " + command + "."); RunThread runThread = new RunThread(command); processThread(runThread, timeout); Process process = runThread.getProcess(); Scanner scanner = new Scanner(process.getInputStream()); scanner.useDelimiter("\\A"); String output = scanner.hasNext() ? scanner.next() : ""; PrintWriter writer = new PrintWriter(outputFileName); writer.write(output); writer.close(); scanner.close(); }
public static void main(String[] args) throws IOException { in = new Scanner(new FileReader("wordFreq.in")); out = new PrintWriter(new FileWriter("wordFreq.out")); WordInfo[] wordTable = new WordInfo[N + 1]; for (int h = 1; h <= N; h++) wordTable[h] = new WordInfo(); int first = -1; // points to first word in alphabetical order int numWords = 0; in.useDelimiter("[^a-zA-Z]+"); while (in.hasNext()) { String word = in.next().toLowerCase(); int loc = search(wordTable, word); if (loc > 0) wordTable[loc].freq++; else // this is a new word if (numWords < MaxWords) { // if table is not full first = addToTable(wordTable, word, -loc, first); ++numWords; } else out.printf("'%s' not added to table\n", word); } printResults(wordTable, first); in.close(); out.close(); } // end main
/** * readFileAndFillArray method. Receives a file and returns an ArrayList filled with the contents * of the file. * * @precondition The file has to exist. * @precondition All values should be positive. * @postcondition Array filled with pebble weights * @param String fileDir file containing the pebbles' weights * @param ArrayList<Pebbles> bagContentsPebble empty array representing one of the bags * @return ArrayList<Integer> bagContents the filled array representing one of the bags * @throws IllegalWeightException * @throws FileNotFoundException */ public static ArrayList<Pebbles> readFileAndFillArray( String fileDir, ArrayList<Pebbles> bagContentsPebble) throws IllegalWeightException, FileNotFoundException { // Get scanner instance Scanner scanner = new Scanner(new FileReader(fileDir)); // Set the delimiter used in file scanner.useDelimiter(","); // Get all tokens and store them a list while (scanner.hasNext()) { String value = scanner.next(); // convert to integer and get rid of extra space with trim int valueInt = Integer.parseInt(value.trim()); // check if the weight is valid if (valueInt >= 0) { bagContentsPebble.add(new Pebbles(valueInt)); } // if the weight is not valid -> warn the user else { scanner.close(); throw new IllegalWeightException(null); } } // Do not forget to close the scanner scanner.close(); return bagContentsPebble; }
public static void main(String[] args) throws Exception { Scanner scan = new Scanner(new File("h:\\tmp\\sample.out")); scan.useDelimiter("\n"); long start = System.currentTimeMillis(); StringBuilder sb = new StringBuilder(); while (scan.hasNext()) { sb.setLength(0); String str = scan.next(); int index = 0; int comma = 0; for (int i = 0; i < str.length(); i++, index++) { if (str.charAt(i) == ',') { comma++; if (comma == 60) { index++; break; } } } sb.append(str.substring(0, index)); } long end = System.currentTimeMillis(); if (scan != null) { scan.close(); } System.out.println("Time : " + (end - start) / 1000.0); }
public static void readParameters(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); Scanner scanner = new Scanner(in); scanner.useDelimiter("[ \t\n,;()]+"); su = scanner.nextInt(); sv = scanner.nextInt(); numImages = su * sv; System.out.println(su + " x " + sv); positions = new double[sv][su][2]; for (int i = 0; i != numImages; ++i) { positions[i / su][i % su][0] = scanner.nextDouble(); positions[i / su][i % su][1] = scanner.nextDouble(); } int numCoefs = scanner.nextInt(); coefs = new double[4][numCoefs]; for (int i = 0; i != 4; ++i) { for (int j = 0; j != numCoefs; ++j) { coefs[i][j] = scanner.nextDouble(); System.out.print(coefs[i][j] + ", "); } System.out.println(); } System.out.println(); // optional? perspectiveX = scanner.nextDouble(); perspectiveY = scanner.nextDouble(); }
public Analyzer(String[] args) { // default p.put("HOSTNAME", "localhost"); p.put("PORT", 1099); p.put("SERVICE", "SuperServicio"); for (int i = 0; i < args.length; i++) { String parameter = args[i]; Scanner scanner = new Scanner(parameter); scanner.useDelimiter("="); String vble = scanner.next(); if (!scanner.hasNext()) { System.err.println(String.format("Parameter %s is incorrect", vble)); continue; } String value = scanner.next(); if (vble.trim().equalsIgnoreCase("PORT")) { try { int port = Integer.parseInt(value); p.put("PORT", port); } catch (NumberFormatException e) { System.err.println( String.format( "Ignoring the incorrect parameter. %s is not a valid port number", value)); } } else { p.put(vble.toUpperCase(), value); } scanner.close(); } }
/** * Loads the achievements placed in the text file in the folder. * * @param textFile name of achievements text file. * @param context of the application. */ public void loadAchievements(String textFile, Context context) { AssetManager assetManager = context.getAssets(); Scanner scanner = null; try { scanner = new Scanner(assetManager.open(textFile + ".txt")); scanner = scanner.useDelimiter(";"); while (scanner.hasNext()) { String name = scanner.next(); String goal = scanner.next(); String postName = scanner.next(); String caption = scanner.next(); String description = scanner.next(); String link = scanner.next(); boolean postOK = Boolean.parseBoolean(scanner.next()); addAchievement(name, goal, postName, caption, description, link, postOK); scanner.nextLine(); } scanner.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * Parses the pizzaString from the dummy database into Product objects * * @param pizzaList Descriptions of the pizzas * @return A list with the new pizzaproducts */ public List<Product> PizzaParsing(String[] pizzaList) { // Variables that are about to be filled String name; Double price; List<String> ingredients = new ArrayList<>(); // Scanning the stringarray and parsing it List<Product> newProductList = new ArrayList<>(); Scanner scan; for (String pizzaString : pizzaList) { scan = new Scanner(pizzaString); scan.useDelimiter("%|, |\\n"); name = scan.next(); String ingredient; while (scan.hasNext()) { ingredient = scan.next(); ingredients.add(ingredient); } String priceString = ingredients.get(ingredients.size() - 1); ingredients.remove(ingredients.size() - 1); scan.close(); scan = new Scanner(priceString); scan.findWithinHorizon("€", 10); price = Double.parseDouble(scan.next()); Product newProduct = new Product(name, price, ProductCategory.PIZZA, ingredients); ingredients.clear(); newProductList.add(newProduct); } return newProductList; }
/** * The read admin list reads in admin objects from a readfile * * @return * @throws FileNotFoundException */ public LinkedList<Admin> readAdminList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("adminList.csv"); LinkedList<Admin> adminList = new LinkedList<Admin>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates admin Admin newAdmin = new Admin(userName, password, email, firstName, lastName, office, phoneNumber); adminList.add(newAdmin); } fstream.close(); } catch (Exception e) { adminList = null; } Collections.sort(adminList); return adminList; }
/** * reads faculty list file * * @return LinkedList<Faculty> * @throws FileNotFoundException */ public LinkedList<Faculty> readFacultyList() throws FileNotFoundException { FileInputStream fstream = new FileInputStream("facultyList.csv"); LinkedList<Faculty> facultyList = new LinkedList<Faculty>(); Scanner input = new Scanner(fstream); input.useDelimiter(","); try { // reads file while (input.hasNext()) { String firstName = input.next(); String lastName = input.next(); String userName = input.next(); String password = input.next(); String email = input.next(); String office = input.next(); String phoneNumber = input.nextLine(); // creates faculty member Faculty newFaculty = new Faculty(userName, password, email, firstName, lastName, office, phoneNumber); facultyList.add(newFaculty); } fstream.close(); } catch (Exception e) { facultyList = null; } Collections.sort(facultyList); return facultyList; }
private boolean isVersionsXmlFile(VFSLeaf fVersions) { if (fVersions == null || !fVersions.exists()) { return false; } InputStream in = fVersions.getInputStream(); if (in == null) { return false; } Scanner scanner = new Scanner(in); scanner.useDelimiter(TAG_PATTERN); boolean foundVersionsTag = false; while (scanner.hasNext()) { String tag = scanner.next(); if ("versions".equals(tag)) { foundVersionsTag = true; break; } } scanner.close(); IOUtils.closeQuietly(in); return foundVersionsTag; }
/** * gets the time from the creeperhost servers * * @return - the time in the DDMMYY format */ public static String getTime() { String content = null; Scanner scanner = null; int retries = 1; try { HttpURLConnection connection = (HttpURLConnection) new URL("http://repo.creeperhost.net/getdate").openConnection(); while (connection.getResponseCode() != 200 && retries <= 3) { connection.disconnect(); connection = (HttpURLConnection) new URL("http://repo" + retries + ".creeperhost.net/getdate").openConnection(); retries++; } scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); connection.disconnect(); } catch (java.net.UnknownHostException uhe) { Logger.logError(uhe.getMessage(), uhe); } catch (Exception ex) { Logger.logError(ex.getMessage(), ex); } finally { if (scanner != null) { scanner.close(); } } return content; }
/** * Checks the file for corruption. * * @param file - File to check * @return - boolean representing if it is valid * @throws IOException */ public static boolean isValid(File file) throws IOException { String content = null; Scanner scanner = null; int retries = 1; try { HttpURLConnection connection = (HttpURLConnection) new URL("http://repo.creeperhost.net/md5/FTB2/" + file.getName()).openConnection(); while (connection.getResponseCode() != 200 && retries <= 3) { connection.disconnect(); connection = (HttpURLConnection) new URL("http://repo" + retries + ".creeperhost.net/md5/FTB2/" + file.getName()) .openConnection(); retries++; } scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); connection.disconnect(); } catch (java.net.UnknownHostException uhe) { Logger.logError(uhe.getMessage(), uhe); } catch (Exception ex) { Logger.logError(ex.getMessage(), ex); } finally { if (scanner != null) { scanner.close(); } } String result = fileMD5(file); Logger.logInfo(result); return content.equalsIgnoreCase(result); }
public static void main(String[] args) throws IOException { // reads in text file Scanner file = new Scanner(new FileReader("input.txt")); String message = file.useDelimiter("\\A").next(); // capitalizes all letters and gets rid of blank spaces message = message.toUpperCase(); message = message.replaceAll("\\s+", ""); int cipher, encrypt_decrypt; // asks user of they want to encrypt or decrypt a message System.out.println("Do you want to encrypt or decrypt?"); System.out.println("1 - Encrypt a message"); System.out.println("2 - Decrypt a message"); encrypt_decrypt = cin.nextInt(); // asks user which algorithm to use System.out.println("Which cipher do you want to use?"); System.out.println("1 - Shift Cipher"); System.out.println("2 - Affine Cipher"); System.out.println("3 - Substitution Cipher"); System.out.println("4 - Vigenere Cipher"); cipher = cin.nextInt(); ciphers(message, cipher, encrypt_decrypt); }
/** * @param filename * @return */ public static String readEntireFileOrDie(String filename) { Scanner scan = getScannerOrDie(filename); scan.useDelimiter("\\Z"); String contents = scan.next(); IO.closeOrLive(scan); return contents; }
/** * gets the time from the creeperhost servers * * @return - the time in the DDMMYY format */ public static String getTime() { String content = null; Scanner scanner = null; String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer())) ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer()) : "http://www.creeperrepo.net"; resolved += "/getdate"; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); if (connection.getResponseCode() != 200) { for (String server : downloadServers.values()) { if (connection.getResponseCode() != 200 && !server.equalsIgnoreCase("www.creeperrepo.net")) { resolved = "http://" + server + "/getdate"; connection = (HttpURLConnection) new URL(resolved).openConnection(); } else if (connection.getResponseCode() == 200) { break; } } } scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); } catch (IOException e) { } finally { connection.disconnect(); if (scanner != null) { scanner.close(); } } return content; }
/* * add a new resource to the node. E.g. the resource temperature or * humidity. If the path is /readings/temp, temp will be a subResource * of readings, which is a subResource of the node. */ public ResourceBase addNodeResource(String path) { Scanner scanner = new Scanner(path); scanner.useDelimiter("/"); String next = ""; boolean resourceExist = false; Resource resource = this; // It's the resource that represents the endpoint ResourceBase subResource = null; while (scanner.hasNext()) { resourceExist = false; next = scanner.next(); for (Resource res : resource.getChildren()) { if (res.getName().equals(next)) { subResource = (ResourceBase) res; resourceExist = true; } } if (!resourceExist) { subResource = new RDTagResource(next, true, this); resource.add(subResource); } resource = subResource; } subResource.setPath(resource.getPath()); subResource.setName(next); scanner.close(); return subResource; }
private void readInventoryFromFile() { try { Scanner scan = new Scanner(new File("inventory.txt")); while (scan.hasNext()) { scan.useDelimiter(", "); String id = scan.next().trim(); String title = scan.next().trim(); scan.useDelimiter("\n"); double price = Double.parseDouble(scan.next().replace(",", "").trim()); Book book = new Book(id, title, price); inventory.add(book); } } catch (FileNotFoundException e) { System.out.println("DEBUG: -----Start-----\n" + e + "DEBUG: ------End------\n"); } }
// method loadServers creates an arraylist of servers from a specified server private void loadServers() { this.servers = new ArrayList<Server>(); File serverDataFile = new File("servers.txt"); String name; String type; int strength; Scanner dataScanner = null; try { // break lines of file out into items to be stored in each element of the arraylist dataScanner = new Scanner(serverDataFile); while (dataScanner.hasNextLine()) { Scanner line = new Scanner(dataScanner.nextLine()); line.useDelimiter(","); name = line.next(); type = line.next(); strength = Integer.parseInt(line.next()); servers.add(new Server(name, type, strength)); // close line scanner line.close(); } } // if file was not found quit program catch (FileNotFoundException e) { System.out.println("Error: Server file not found."); System.exit(0); } }
public static int getTimeID(String time) { Scanner in = new Scanner(time); in.useDelimiter(","); String day = in.next(); System.out.println(day); String begin = in.next(); System.out.println(begin); String end = in.next(); System.out.println(end); in.close(); System.out.println("getTimeID started"); ResultSet rs = runQuery( "SELECT time_id FROM schedule.timeblock WHERE " + "day='" + day + "' AND begin='" + begin + "' AND end='" + end + "';"); try { if (rs.next()) { return rs.getInt("time_id"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; }