List of usage examples for java.util Scanner hasNextLine
public boolean hasNextLine()
From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java
public static ArrayList<String> updateProjectJobFiles(File projectFile, File projectConfigDirectory, ArrayList<String> receivedJobNames) throws IOException { Scanner scanner = new Scanner(projectFile); ArrayList<String> updatedJobs = new ArrayList<String>(); ArrayList<String> newJobs = new ArrayList<String>(); ArrayList<String> deletedJobs = new ArrayList<String>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (receivedJobNames.contains(line)) { updatedJobs.add(line);/*from www . jav a2s. c om*/ receivedJobNames.remove(line); } else { deletedJobs.add(line); } } logger.info("There are " + receivedJobNames.size() + " new jobs"); logger.info("There are " + deletedJobs.size() + " deleted jobs"); logger.info("There are " + updatedJobs.size() + " updated jobs"); for (String s : receivedJobNames) { newJobs.add(s); } scanner.close(); FileWriter writer = new FileWriter(projectFile, false); for (String s : updatedJobs) { writer.write(s); writer.write("\n"); } for (String s : newJobs) { writer.write(s); writer.write("\n"); } writer.close(); return deletedJobs; }
From source file:ProfileManager.java
/** * Loads the configuration file, whose name is identified by * <code>DATA_FILE_NAME</code>, into memory. * /*from w ww .j av a 2 s .co m*/ * <p><code>scanBackups()</code> is assumed to have already run before this * method runs. It then verifies that each character folder contained * within is matched with a corresponding entry in * <code>characters</code></p> * * @param file <code>File</code> object, whose name is determined by * <code>DATA_FILE_NAME</code>. * * @return <code>null String</code> TODO: fix this */ //private static String loadConfig(File file) { private static boolean loadConfig(File file) { // TODO: Iterate through character folders in 'FFXIV_FOLDER' and look for ones that are not identified in the 'characters' identifier. System.out.println("Loading " + DATA_FILE_NAME); Scanner scanner = null; try { scanner = new Scanner(file); } catch (Exception e) { System.out.println("loadConfig() exception!"); return false; } if (scanner.hasNextLine()) { //return scanner.next(); return true; } String name = ""; // TODO: Store the active character name from the config file into 'name'. // NOTE: activeCharacterName and activeCharacterID must be known for // getActiveProfile() to succeed. activeCharacterName = name; activeCharacter = getCharacter(name); activeCharacterID = activeCharacter.getId(); activeProfile = getActiveProfile(name); return false; }
From source file:com.google.api.ads.adwords.keywordoptimizer.KeywordOptimizer.java
/** * Reads settings (keywords / urls / serach terms) line-by-line from a file. * * @param fileName the name of the file to read from * @return a {@link List} of strings line-by-line * @throws KeywordOptimizerException in case there is a problem reading the file *//*from w ww . j a va2 s . c o m*/ private static List<String> loadFromFile(String fileName) throws KeywordOptimizerException { List<String> out = new ArrayList<String>(); Scanner scan = null; try { scan = new Scanner(new File(fileName)); while (scan.hasNextLine()) { String line = scan.nextLine().trim(); // Ignore comment lines. if (line.startsWith("#")) { continue; } out.add(line); } return out; } catch (IOException e) { throw new KeywordOptimizerException("Error loading file '" + fileName + "'", e); } finally { if (scan != null) { scan.close(); } } }
From source file:clummy.classes.DataHandlingClass.java
/** * to read file by line and pass each line to arraylist * only read starting at the third line//w ww.ja v a 2 s . c om * @param fileName String * @return ArrayList */ public static ArrayList<String> readFile(String fileName) { ArrayList<String> readList = new ArrayList<>(); Scanner scan; try { scan = new Scanner(new FileReader(fileName)); int lineCount = 0; while (scan.hasNextLine()) { lineCount++; if (lineCount <= 3) scan.nextLine(); if (lineCount >= 4) readList.add(scan.nextLine()); } scan.close(); } catch (FileNotFoundException ex) { Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex); } return readList; }
From source file:net.dv8tion.jda.player.Playlist.java
public static Playlist getPlaylist(String url) { List<String> infoArgs = new LinkedList<>(); infoArgs.addAll(YOUTUBE_DL_PLAYLIST_ARGS); infoArgs.add("--"); //Url separator. Deals with YT ids that start with -- infoArgs.add(url);//from w w w. ja v a 2 s .co m //Fire up Youtube-dl and get all sources from the provided url. List<AudioSource> sources = new ArrayList<>(); Scanner scan = null; try { Process infoProcess = new ProcessBuilder().command(infoArgs).start(); byte[] infoData = IOUtils.readFully(infoProcess.getInputStream(), -1, false); if (infoData == null || infoData.length == 0) throw new NullPointerException( "The YT-DL playlist process resulted in a null or zero-length INFO!"); String sInfo = new String(infoData); scan = new Scanner(sInfo); JSONObject source = new JSONObject(scan.nextLine()); if (source.has("_type"))//Is a playlist { sources.add(new RemoteSource(source.getString("url"))); while (scan.hasNextLine()) { source = new JSONObject(scan.nextLine()); sources.add(new RemoteSource(source.getString("url"))); } } else //Single source link { sources.add(new RemoteSource(source.getString("webpage_url"))); } } catch (IOException e) { e.printStackTrace(); } finally { if (scan != null) scan.close(); } //Now that we have all the sources we can create our Playlist object. Playlist playlist = new Playlist("New Playlist"); playlist.sources = sources; return playlist; }
From source file:org.apache.flink.yarn.YarnTestBase.java
/** * This method checks the written TaskManager and JobManager log files * for exceptions.//w w w . ja va 2s . co m * * WARN: Please make sure the tool doesn't find old logfiles from previous test runs. * So always run "mvn clean" before running the tests here. * */ public static void ensureNoProhibitedStringInLogFiles(final String[] prohibited, final String[] whitelisted) { File cwd = new File("target/" + yarnConfiguration.get(TEST_CLUSTER_NAME_KEY)); Assert.assertTrue("Expecting directory " + cwd.getAbsolutePath() + " to exist", cwd.exists()); Assert.assertTrue("Expecting directory " + cwd.getAbsolutePath() + " to be a directory", cwd.isDirectory()); File foundFile = findFile(cwd.getAbsolutePath(), new FilenameFilter() { @Override public boolean accept(File dir, String name) { // scan each file for prohibited strings. File f = new File(dir.getAbsolutePath() + "/" + name); try { Scanner scanner = new Scanner(f); while (scanner.hasNextLine()) { final String lineFromFile = scanner.nextLine(); for (String aProhibited : prohibited) { if (lineFromFile.contains(aProhibited)) { boolean whitelistedFound = false; for (String white : whitelisted) { if (lineFromFile.contains(white)) { whitelistedFound = true; break; } } if (!whitelistedFound) { // logging in FATAL to see the actual message in TRAVIS tests. Marker fatal = MarkerFactory.getMarker("FATAL"); LOG.error(fatal, "Prohibited String '{}' in line '{}'", aProhibited, lineFromFile); return true; } } } } } catch (FileNotFoundException e) { LOG.warn("Unable to locate file: " + e.getMessage() + " file: " + f.getAbsolutePath()); } return false; } }); if (foundFile != null) { Scanner scanner = null; try { scanner = new Scanner(foundFile); } catch (FileNotFoundException e) { Assert.fail("Unable to locate file: " + e.getMessage() + " file: " + foundFile.getAbsolutePath()); } LOG.warn("Found a file with a prohibited string. Printing contents:"); while (scanner.hasNextLine()) { LOG.warn("LINE: " + scanner.nextLine()); } Assert.fail("Found a file " + foundFile + " with a prohibited string: " + Arrays.toString(prohibited)); } }
From source file:dsfixgui.FileIO.DSFixFileController.java
/** *Writes a string to a text file/*ww w. j ava 2 s.c o m*/ * * @param filePath * the path of the file to be read, including the filename * @param text * the String to be written to the file; can be more than one line. * @param overwrite * determines whether the user wants to overwrite the write file if it * already exists. If true, pre-existing file will be overwritten * @throws IIOException * if the write file already exists and the user allowed overwriting, but * the file could not be overwritten * @throws AccessDeniedException * if the write file already exists but the user didn't allow overwriting * @throws IOException * if an error occurs initializing the BufferedWriter */ public static void writeTextFile(String filePath, String text, boolean overwrite) throws IIOException, IOException, AccessDeniedException { //The file to be written File writeFile = new File(filePath); if (writeFile.exists() && overwrite) { //If file exists, try to delete it if (!writeFile.delete()) { //If file cannot be deleted, throw OIOException throw new IIOException("Could not delete pre-existing file: " + filePath); } } else if (writeFile.exists() && !overwrite) { //If file exists but is not allowed to be overwritten, throw AccessDeniedException throw new AccessDeniedException(writeFile.getPath()); } //Format each linebreak to be displayed correctly in a text file String formattedText = text.replaceAll("\n", String.format("%n")); //Initialize BufferedWriter to write string to file BufferedWriter fileWriter = new BufferedWriter(new FileWriter(writeFile)); //Write the file Scanner scanner = new Scanner(formattedText); while (scanner.hasNextLine()) { fileWriter.write(scanner.nextLine()); fileWriter.newLine(); } fileWriter.close(); }
From source file:com.cisco.dbds.utils.tims.TIMS.java
/** * Readhtmlfile pass.// ww w. j av a 2s .co m * * @return the array list * @throws FileNotFoundException the file not found exception */ public static ArrayList<String> readhtmlfilePass() throws FileNotFoundException { ArrayList<String> re = new ArrayList<String>(); String fEncoding = "UTF-8"; String tt = ""; int fcount = 0; Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding); try { while (scanner.hasNextLine()) { tt = scanner.nextLine(); tt = tt.trim(); if (tt.contains("Failed Test Case ID")) fcount = 1; if (fcount == 0 && tt.contains("Ttv") && !(tt.contains("Precheck")) && !(tt.contains("Precondition"))) { System.out.println("LINE read: " + tt); String a[] = tt.split("<td>"); System.out.println("tcid: " + a[3].substring(a[3].indexOf('T'), 19)); System.out.println("Desc: " + a[5].substring(0, a[5].indexOf("<"))); System.out.println("status: " + a[6].substring(a[6].indexOf(">") + 1, a[6].indexOf("d") + 1)); String aa = a[3].substring(a[3].indexOf('T'), 19) + "~" + a[5].substring(0, a[5].indexOf("<")) + "~" + a[6].substring(a[6].indexOf(">") + 1, a[6].indexOf("d") + 1); re.add(aa); } } } finally { scanner.close(); } return re; }
From source file:dsfixgui.FileIO.DSFixFileController.java
public static String readTextFile(String filePath) throws FileNotFoundException { //The file to be read File readFile = new File(filePath); //Initialize Scanner for reading file Scanner fileReader = new Scanner(readFile); //The String to be returned String text = null;/*from w w w. j a va2 s . co m*/ while (fileReader.hasNextLine()) { if (text == null) { //Initialize return String text = ""; } else { //Add new linebreak text += String.format("%n"); } //Add line to text text += fileReader.nextLine(); } fileReader.close(); return text; }
From source file:hyperheuristics.main.comparisons.CompareHypervolumes.java
private static void hypervolumeComparison(String[] problems, String[] heuristicFunctions, int numberOfObjectives) throws InterruptedException, IOException { for (String heuristicFunction : heuristicFunctions) { String path = outpath;// ww w. j a v a2s . c om String outputDirectory = path + numberOfObjectives + "objectives/" + heuristicFunction + "/"; try (FileWriter fileWriter = new FileWriter(outputDirectory + "HYPERVOLUMES.txt")) { int hyperheuristicBest = 0; int mecbaBest = 0; int tied = 0; int hyperheuristicBestMean = 0; int mecbaBestMean = 0; int tiedMean = 0; int equivalent = 0; for (String problem : problems) { fileWriter.append("Hypervolume comparison for " + problem + ":\n"); fileWriter.append("\n"); HypervolumeHandler hypervolumeHandler = new HypervolumeHandler(); String hyperheuristicDirectory = outputDirectory + problem + "/"; String mecbaDirectory = "resultado/nsgaii/" + problem + "_Comb_" + numberOfObjectives + "obj/"; //Best hypervolume for PFknown hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "FUN.txt"); hypervolumeHandler.addParetoFront(mecbaDirectory + "All_FUN_nsgaii-" + problem); double mecbaHypervolume = hypervolumeHandler .calculateHypervolume(mecbaDirectory + "All_FUN_nsgaii-" + problem, numberOfObjectives); double hyperheuristicHypervolume = hypervolumeHandler .calculateHypervolume(hyperheuristicDirectory + "FUN.txt", numberOfObjectives); fileWriter.append("MECBA PFknown: " + mecbaHypervolume + "\n"); fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicHypervolume + "\n"); if (mecbaHypervolume == hyperheuristicHypervolume) { fileWriter.append("Best PFknown: Tied!\n"); tied++; } else { if (mecbaHypervolume > hyperheuristicHypervolume) { fileWriter.append("Best PFknown: MECBA\n"); mecbaBest++; } else { fileWriter.append("Best PFknown: " + heuristicFunction + "\n"); hyperheuristicBest++; } } //Best mean hypervolume fileWriter.append("\n"); hypervolumeHandler.clear(); for (int i = 0; i < EXECUTIONS; i++) { hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt"); hypervolumeHandler.addParetoFront( mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas"); } double[] mecbaHypervolumes = new double[EXECUTIONS]; double[] hyperheuristicHypervolumes = new double[EXECUTIONS]; mecbaHypervolume = 0; hyperheuristicHypervolume = 0; for (int i = 0; i < EXECUTIONS; i++) { mecbaHypervolumes[i] = hypervolumeHandler.calculateHypervolume( mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas", numberOfObjectives); mecbaHypervolume += mecbaHypervolumes[i]; hyperheuristicHypervolumes[i] = hypervolumeHandler.calculateHypervolume( hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt", numberOfObjectives); hyperheuristicHypervolume += hyperheuristicHypervolumes[i]; } mecbaHypervolume /= (double) EXECUTIONS; hyperheuristicHypervolume /= (double) EXECUTIONS; fileWriter.append("MECBA (Mean): " + mecbaHypervolume + "\n"); fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicHypervolume + "\n"); if (mecbaHypervolume == hyperheuristicHypervolume) { fileWriter.append("Best (Mean): Tied!\n"); tiedMean++; } else { if (mecbaHypervolume > hyperheuristicHypervolume) { fileWriter.append("Best (Mean): MECBA\n"); mecbaBestMean++; } else { fileWriter.append("Best (Mean): " + heuristicFunction + "\n"); hyperheuristicBestMean++; } String script = ""; script += "MECBA <- c("; for (double value : mecbaHypervolumes) { script += value + ","; } script = script.substring(0, script.lastIndexOf(",")) + ")"; script += "\n"; script += "MECBA_Hyp <- c("; for (double value : hyperheuristicHypervolumes) { script += value + ","; } script = script.substring(0, script.lastIndexOf(",")) + ")"; script += "\n"; script += "require(pgirmess)\n"; script += "AR1 <- cbind(MECBA, MECBA_Hyp)\n"; script += "result <- friedman.test(AR1)\n"; script += "m <- data.frame(result$statistic,result$p.value)\n"; script += "pos_teste <- friedmanmc(AR1)\n"; script += "print(pos_teste)"; try (FileWriter scriptWriter = new FileWriter(hyperheuristicDirectory + "temp_input.txt")) { scriptWriter.append(script); } ProcessBuilder processBuilder = new ProcessBuilder("R", "--no-save"); File tempOutput = new File(hyperheuristicDirectory + "temp_output.txt"); processBuilder.redirectOutput(tempOutput); File tempInput = new File(hyperheuristicDirectory + "temp_input.txt"); processBuilder.redirectInput(tempInput); Process process = processBuilder.start(); process.waitFor(); Scanner scanner = new Scanner(tempOutput); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("FALSE")) { equivalent++; fileWriter.append("Statistical Equivalents (Friedman 5%)\n"); break; } } tempInput.delete(); tempOutput.delete(); } fileWriter.append("\n"); fileWriter.append("----------\n"); fileWriter.append("\n"); } fileWriter.append("Problems: " + problems.length + "\n"); fileWriter.append("\n"); fileWriter.append("Tied PFknown: " + tied + "\n"); fileWriter.append("MECBA PFknown: " + mecbaBest + "\n"); fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicBest + "\n"); fileWriter.append("\n"); fileWriter.append("Tied (Mean): " + tiedMean + "\n"); fileWriter.append("MECBA (Mean): " + mecbaBestMean + "\n"); fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicBestMean + "\n"); fileWriter.append("Statistically Equivalent: " + equivalent + "\n"); } } }