List of usage examples for java.util Scanner hasNextLine
public boolean hasNextLine()
From source file:dsfixgui.FileIO.DSFixFileController.java
public void turnOffIngameAA() { ui.printConsole(TURNING_OFF_AA);// w w w . ja va2 s .com if (System.getenv("AppData") != null) { ui.printConsole(FOUND_APPDATA); File iniFile = new File( System.getenv("AppData").substring(0, System.getenv("AppData").indexOf(APPDATA)) + APPDATA_INI); if (iniFile.exists()) { Scanner fileReader; try { fileReader = new Scanner(iniFile); } catch (FileNotFoundException ex) { ui.printConsole(UNABLE_TO_READ_DS_INI); couldntTurnOffAA(); return; } int linesRead; String editedIniBuffer = ""; for (linesRead = 0; linesRead <= 60 && fileReader.hasNextLine(); linesRead++) { //Begin reading DarkSouls.ini String line = fileReader.nextLine(); if (line.contains(AA_SETTING)) { //Change this line of the .ini file line = AA_SETTING + " = 0"; } line += String.format("%n"); editedIniBuffer += line; } if (linesRead == 61) { //All lines were read without issue, now write file try { ui.printConsole(WRITING_FILE[0]); BufferedWriter fileWriter = new BufferedWriter(new FileWriter(iniFile)); fileWriter.write(editedIniBuffer); fileWriter.close(); //Write was successful ui.printConsole(WRITING_FILE[1] + " " + TURNED_OFF_AA); } catch (IOException ex) { ui.printConsole(IOEX_FILE_WRITER); ui.printConsole(FILE_WRITE_FAILED + " " + SEE_CONSOLE); couldntTurnOffAA(); } } else { ui.printConsole(UNABLE_TO_READ_DS_INI + " " + linesRead); couldntTurnOffAA(); } } else { ui.printConsole(UNABLE_TO_FIND_DS_INI); File template = new File(TEMPLATES_DIR + "\\" + DS_INI); ui.printConsole(CREATING_INI); try { FileUtils.copyFile(template, iniFile); ui.printConsole(TURNED_OFF_AA); } catch (IOException ioe) { couldntTurnOffAA(); } } } else { ui.printConsole(UNABLE_TO_FIND_APPDATA); couldntTurnOffAA(); } }
From source file:dsfixgui.view.DSFGraphicsPane.java
private String getFPSFixKey() { File fpsFixCfg = new File(ui.getDataFolder() + "\\" + FPS_FIX_FILES[1]); if (fpsFixCfg.exists()) { try {//from w ww .jav a2 s . c o m Scanner fpsFixKeyScanner = new Scanner(fpsFixCfg); while (fpsFixKeyScanner.hasNextLine()) { String line = fpsFixKeyScanner.nextLine(); if (line.startsWith("Key=")) { fpsFixKeyScanner.close(); return line.substring(line.indexOf("Key=") + 4); } } } catch (FileNotFoundException ex) { //Logger.getLogger(DSFGraphicsPane.class.getName()).log(Level.SEVERE, null, ex); return null; } } else { return null; } return null; }
From source file:ml.shifu.shifu.core.processor.VarSelectModelProcessor.java
private int persistColumnIds(Path path) { try {//ww w. j av a 2 s . co m List<Scanner> scanners = ShifuFileUtils.getDataScanners(path.toString(), modelConfig.getDataSet().getSource()); List<Integer> ids = null; for (Scanner scanner : scanners) { while (scanner.hasNextLine()) { String[] raw = scanner.nextLine().trim().split("\\|"); @SuppressWarnings("unused") int idSize = Integer.parseInt(raw[0]); ids = CommonUtils.stringToIntegerList(raw[1]); } } // prevent multiply running setting for (ColumnConfig config : columnConfigList) { if (!config.isForceSelect()) { config.setFinalSelect(Boolean.FALSE); } } for (Integer id : ids) { this.columnConfigList.get(id).setFinalSelect(Boolean.TRUE); } super.saveColumnConfigList(); } catch (IOException e) { e.printStackTrace(); return -1; } catch (IllegalArgumentException e) { e.printStackTrace(); return -1; } return 0; }
From source file:dsfixgui.view.DSFGraphicsPane.java
public void setFPSFixKey(String newFPSFixKey) { try {// w w w.ja va 2s . c o m String fpsFixCfg = readTextFile(ui.getDataFolder() + "\\" + FPS_FIX_FILES[1]); ui.printConsole(WRITING_FILE[0] + FPS_FIX_FILES[1] + "..."); //The file to be written File writeFile = new File(ui.getDataFolder() + "\\" + FPS_FIX_FILES[1]); if (writeFile.exists()) { //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: " + FPS_FIX_FILES[1]); } } //Format each linebreak to be displayed correctly in a text file String formattedText = fpsFixCfg.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); int i = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("Key=")) { fileWriter.write("Key=" + newFPSFixKey); fileWriter.newLine(); i++; } else if (line.length() > 1) { fileWriter.write(line); fileWriter.newLine(); i++; } else if (i == 2 || i == 4) { fileWriter.newLine(); i++; } } fileWriter.close(); scanner.close(); ui.printConsole(WRITING_FILE[1]); } catch (IOException ex) { ui.printConsole(FILES_EDITED_ERR[0] + FPS_FIX_FILES[1]); fpsFixKeyPicker.setDisable(true); } }
From source file:org.apache.accumulo.core.util.shell.Shell.java
public int start() throws IOException { if (configError) return 1; String input;/*from w w w . jav a 2s . c om*/ if (isVerbose()) printInfo(); String home = System.getProperty("HOME"); if (home == null) home = System.getenv("HOME"); String configDir = home + "/" + HISTORY_DIR_NAME; String historyPath = configDir + "/" + HISTORY_FILE_NAME; File accumuloDir = new File(configDir); if (!accumuloDir.exists() && !accumuloDir.mkdirs()) log.warn("Unable to make directory for history at " + accumuloDir); try { final FileHistory history = new FileHistory(new File(historyPath)); reader.setHistory(history); // Add shutdown hook to flush file history, per jline javadocs Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { history.flush(); } catch (IOException e) { log.warn("Could not flush history to file."); } } }); } catch (IOException e) { log.warn("Unable to load history file at " + historyPath); } // Turn Ctrl+C into Exception instead of JVM exit reader.setHandleUserInterrupt(true); ShellCompletor userCompletor = null; if (execFile != null) { java.util.Scanner scanner = new java.util.Scanner(execFile, Constants.UTF8.name()); try { while (scanner.hasNextLine() && !hasExited()) { execCommand(scanner.nextLine(), true, isVerbose()); } } finally { scanner.close(); } } else if (execCommand != null) { for (String command : execCommand.split("\n")) { execCommand(command, true, isVerbose()); } return exitCode; } while (true) { try { if (hasExited()) return exitCode; // If tab completion is true we need to reset if (tabCompletion) { if (userCompletor != null) reader.removeCompleter(userCompletor); userCompletor = setupCompletion(); reader.addCompleter(userCompletor); } reader.setPrompt(getDefaultPrompt()); input = reader.readLine(); if (input == null) { reader.println(); return exitCode; } // User Canceled (Ctrl+D) execCommand(input, disableAuthTimeout, false); } catch (UserInterruptException uie) { // User Cancelled (Ctrl+C) reader.println(); String partialLine = uie.getPartialLine(); if (partialLine == null || "".equals(uie.getPartialLine().trim())) { // No content, actually exit return exitCode; } } finally { reader.flush(); } } }
From source file:de.evaluationtool.gui.EvaluationFrame.java
public String[][] loadNT(File f) throws FileNotFoundException { List<String[]> rows = new LinkedList<String[]>(); Scanner in = new Scanner(f); while (in.hasNextLine()) { String line = in.nextLine(); String[] tokens = line.split("\\s"); // remove <> signs String entity1 = tokens[0].substring(1, tokens[0].length() - 1); setProperty(tokens[1]);/*from www. j a v a 2 s . c om*/ String entity2 = tokens[2].substring(1, tokens[2].length() - 1); String[] row = new String[] { entity1, getProperty(), entity2 }; rows.add(row); } in.close(); return rows.toArray(new String[0][]); }
From source file:azkaban.viewer.reportal.ReportalServlet.java
/** * Returns a list of file Objects that contain a "name" property with the file name, * a "content" property with the lines in the file, and a "hasMore" property if the * file contains more than NUM_PREVIEW_ROWS lines. * @param fileList/*from w ww .j a v a 2s . c o m*/ * @param locationFull * @param streamProvider * @return */ private List<Object> getFilePreviews(String[] fileList, String locationFull, IStreamProvider streamProvider) { List<Object> files = new ArrayList<Object>(); InputStream csvInputStream = null; try { for (String fileName : fileList) { Map<String, Object> file = new HashMap<String, Object>(); file.put("name", fileName); String filePath = locationFull + "/" + fileName; csvInputStream = streamProvider.getFileInputStream(filePath); Scanner rowScanner = new Scanner(csvInputStream); List<Object> lines = new ArrayList<Object>(); int lineNumber = 0; while (rowScanner.hasNextLine() && lineNumber < ReportalMailCreator.NUM_PREVIEW_ROWS) { String csvLine = rowScanner.nextLine(); String[] data = csvLine.split("\",\""); List<String> line = new ArrayList<String>(); for (String item : data) { String column = StringEscapeUtils.escapeHtml(item.replace("\"", "")); line.add(column); } lines.add(line); lineNumber++; } file.put("content", lines); if (rowScanner.hasNextLine()) { file.put("hasMore", true); } files.add(file); rowScanner.close(); } } catch (Exception e) { logger.debug("Error encountered while processing files in " + locationFull, e); } finally { IOUtils.closeQuietly(csvInputStream); } return files; }
From source file:org.apache.oozie.action.hadoop.TestMapReduceActionExecutor.java
public void _testMapReduceWithUberJar() throws Exception { FileSystem fs = getFileSystem(); Path inputDir = new Path(getFsTestCaseDir(), "input"); Path outputDir = new Path(getFsTestCaseDir(), "output"); Writer w = new OutputStreamWriter(fs.create(new Path(inputDir, "data.txt"))); w.write("dummy\n"); w.write("dummy\n"); w.close();/*from www .j ava 2 s . co m*/ String actionXml = "<map-reduce>" + "<job-tracker>" + getJobTrackerUri() + "</job-tracker>" + "<name-node>" + getNameNodeUri() + "</name-node>" + getMapReduceUberJarConfig(inputDir.toString(), outputDir.toString()).toXmlString(false) + "</map-reduce>"; String jobID = _testSubmit("map-reduce", actionXml); boolean containsLib1Jar = false; String lib1JarStr = "jobcache/" + jobID + "/jars/lib/lib1.jar"; Pattern lib1JarPatYarn = Pattern.compile(".*appcache/application_" + jobID.replaceFirst("job_", "") + "/filecache/.*/uber.jar/lib/lib1.jar.*"); boolean containsLib2Jar = false; String lib2JarStr = "jobcache/" + jobID + "/jars/lib/lib1.jar"; Pattern lib2JarPatYarn = Pattern.compile(".*appcache/application_" + jobID.replaceFirst("job_", "") + "/filecache/.*/uber.jar/lib/lib2.jar.*"); FileStatus[] fstats = getFileSystem().listStatus(outputDir); for (FileStatus fstat : fstats) { Path p = fstat.getPath(); if (getFileSystem().isFile(p) && p.getName().startsWith("part-")) { InputStream is = getFileSystem().open(p); Scanner sc = new Scanner(is); while (sc.hasNextLine()) { String line = sc.nextLine(); containsLib1Jar = (containsLib1Jar || line.contains(lib1JarStr) || lib1JarPatYarn.matcher(line).matches()); containsLib2Jar = (containsLib2Jar || line.contains(lib2JarStr) || lib2JarPatYarn.matcher(line).matches()); } sc.close(); is.close(); } } assertTrue( "lib/lib1.jar should have been unzipped from the uber jar and added to the classpath but was not", containsLib1Jar); assertTrue( "lib/lib2.jar should have been unzipped from the uber jar and added to the classpath but was not", containsLib2Jar); }
From source file:uk.ac.soton.itinnovation.sad.service.services.PluginsService.java
/** * Returns all plugins metadata directly from the file system. * * @return/*from w w w .ja v a 2 s.c o m*/ */ public final JSONObject getLivePluginsInfo() { logger.debug("Returning plugins using property name: " + PLUGIN_PROPERTY_NAME); // JSONObject pluginsRoot = propertiesService.getLiveProperties().getJSONObject(PLUGIN_PROPERTY_NAME); String pluginsPath = configurationService.getConfiguration().getPluginsPath(); logger.debug("Plugins folder filepath from configuration: " + pluginsPath); File pluginsFolder = new File(pluginsPath); JSONObject result = new JSONObject(); if (!pluginsFolder.isDirectory()) { throw new RuntimeException( "Plugins path does not exist or not a folder: " + pluginsFolder.getAbsolutePath()); } else { File filenamesInPluginsFolder[] = pluginsFolder.listFiles(); File tempFile, testConfig; Scanner scanner; StringBuilder fileContents; String pluginConfigAsString; for (int i = 0; i < filenamesInPluginsFolder.length; i++) { tempFile = filenamesInPluginsFolder[i]; if (tempFile.isDirectory()) { logger.debug("Looking in: " + tempFile.getAbsolutePath()); testConfig = new File( tempFile.getAbsolutePath() + fileSeparator + PLUGIN_CONFIGURATION_FILE_NAME); if (!testConfig.exists()) { logger.debug("Missing configuration file in: " + tempFile.getAbsolutePath()); } else { logger.debug("Looking for plugin configuration in: " + tempFile.getAbsolutePath()); pluginConfigAsString = ""; fileContents = new StringBuilder((int) testConfig.length()); try { scanner = new Scanner(testConfig); while (scanner.hasNextLine()) { fileContents.append(scanner.nextLine()); fileContents.append(lineSeparator); } scanner.close(); pluginConfigAsString = fileContents.toString(); } catch (FileNotFoundException ex) { throw new RuntimeException("Failed to read plugin configuration file", ex); } if (pluginConfigAsString.length() < 1) { logger.error("No configuration found in: " + tempFile.getAbsolutePath()); } else { logger.debug("Found plugin configuration: " + pluginConfigAsString); JSONObject foundConfig = JSONObject.fromObject(pluginConfigAsString); boolean addPluginToResult = true; if (foundConfig.containsKey("enabled")) { if (foundConfig.getString("enabled").equals("n")) { addPluginToResult = false; } } if (addPluginToResult) { logger.debug("Adding pluginFolder to configuration: " + tempFile.getName()); foundConfig.put("pluginFolder", tempFile.getName()); String pluginName; if (foundConfig.containsKey("name")) { pluginName = foundConfig.getString("name"); logger.debug("Saving plugin configuration with name: " + pluginName); result.put(pluginName, foundConfig); } else { pluginName = tempFile.getName(); logger.error("Plugin name not found in configuration! Saving with file name: " + pluginName); result.put(pluginName, foundConfig); } } else { logger.debug("Plugin disabled in configuration, skipping: " + foundConfig.getString("name")); } } } } else { logger.debug("Ignoring: " + tempFile.getAbsolutePath()); } } } return result; }
From source file:org.apache.accumulo.shell.Shell.java
public int start() throws IOException { String input;/*w w w . j av a 2 s . co m*/ if (isVerbose()) printInfo(); String home = System.getProperty("HOME"); if (home == null) home = System.getenv("HOME"); String configDir = home + "/" + HISTORY_DIR_NAME; String historyPath = configDir + "/" + HISTORY_FILE_NAME; File accumuloDir = new File(configDir); if (!accumuloDir.exists() && !accumuloDir.mkdirs()) log.warn("Unable to make directory for history at " + accumuloDir); try { final FileHistory history = new FileHistory(new File(historyPath)); reader.setHistory(history); // Add shutdown hook to flush file history, per jline javadocs Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { history.flush(); } catch (IOException e) { log.warn("Could not flush history to file."); } } }); } catch (IOException e) { log.warn("Unable to load history file at " + historyPath); } // Turn Ctrl+C into Exception instead of JVM exit reader.setHandleUserInterrupt(true); ShellCompletor userCompletor = null; if (execFile != null) { java.util.Scanner scanner = new java.util.Scanner(execFile, UTF_8.name()); try { while (scanner.hasNextLine() && !hasExited()) { execCommand(scanner.nextLine(), true, isVerbose()); } } finally { scanner.close(); } } else if (execCommand != null) { for (String command : execCommand.split("\n")) { execCommand(command, true, isVerbose()); } return exitCode; } while (true) { try { if (hasExited()) return exitCode; // If tab completion is true we need to reset if (tabCompletion) { if (userCompletor != null) reader.removeCompleter(userCompletor); userCompletor = setupCompletion(); reader.addCompleter(userCompletor); } reader.setPrompt(getDefaultPrompt()); input = reader.readLine(); if (input == null) { reader.println(); return exitCode; } // User Canceled (Ctrl+D) execCommand(input, disableAuthTimeout, false); } catch (UserInterruptException uie) { // User Cancelled (Ctrl+C) reader.println(); String partialLine = uie.getPartialLine(); if (partialLine == null || "".equals(uie.getPartialLine().trim())) { // No content, actually exit return exitCode; } } finally { reader.flush(); } } }