Java Code Examples for java.util.Scanner#hasNextLine()

The following examples show how to use java.util.Scanner#hasNextLine() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LegacyProcessHandler.java    From appengine-plugins-core with Apache License 2.0 6 votes vote down vote up
private Thread handleStdOut(Process process) {
  final Scanner stdOut = new Scanner(process.getInputStream(), StandardCharsets.UTF_8.name());
  Thread stdOutThread =
      new Thread("standard-out") {
        @Override
        public void run() {
          while (stdOut.hasNextLine() && !Thread.interrupted()) {
            String line = stdOut.nextLine();
            for (ProcessOutputLineListener stdOutLineListener : stdOutLineListeners) {
              stdOutLineListener.onOutputLine(line);
            }
          }
          stdOut.close();
        }
      };
  stdOutThread.setDaemon(true);
  stdOutThread.start();
  return stdOutThread;
}
 
Example 2
Source File: PluginMessagesCLIResult.java    From thym with Eclipse Public License 1.0 6 votes vote down vote up
private void parseMessage(){
	
	Scanner scanner = new Scanner(getMessage());
	
	while(scanner.hasNextLine()){
		//check of --variable APP_ID=value is needed
		if( scanner.findInLine("(?:\\s\\-\\-variable\\s(\\w*)=value)") != null ){
			MatchResult mr = scanner.match();
			StringBuilder missingVars = new StringBuilder();
			for(int i = 0; i<mr.groupCount();i++){
				if(i>0){
					missingVars.append(",");
				}
				missingVars.append(mr.group());
			}
			pluginStatus = new HybridMobileStatus(IStatus.ERROR, HybridCore.PLUGIN_ID, CordovaCLIErrors.ERROR_MISSING_PLUGIN_VARIABLE,
					NLS.bind("This plugin requires {0} to be defined",missingVars), null);
		
		}
		scanner.nextLine();
	}
	scanner.close();
	
}
 
Example 3
Source File: ShellExecutor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  Thread.currentThread().setName("Shell Executor IO Forwarder thread " + (error ? "stderr" : "stdout"));

  try {
    InputStreamReader reader = new InputStreamReader(inputStream);
    Scanner scan = new Scanner(reader);
    while (scan.hasNextLine()) {
      if (error) {
        LOG.error("stderr: " + scan.nextLine());
      } else {
        LOG.info("stdout: " + scan.nextLine());
      }
    }
  } finally {
    IOUtils.closeQuietly(inputStream);
  }
}
 
Example 4
Source File: ErrorDetectingCLIResult.java    From thym with Eclipse Public License 1.0 6 votes vote down vote up
private void parseErrors(){
	final Scanner scanner = new Scanner(getMessage());
	boolean error = false;
	while(scanner.hasNextLine()){
		String line = scanner.nextLine();
		line = line.trim();// remove leading whitespace
		if(line.startsWith(ERROR_PREFIX)){
			error = true;
			errorMessage = errorMessage.append(line.substring(ERROR_PREFIX.length(), line.length()).trim());
		}else if(line.contains("command not found") || line.contains("is not recognized as an internal or external command")){
			error = true;
			errorMessage.append(CORDOVA_NOT_FOUND);
			errorCode = CordovaCLIErrors.ERROR_COMMAND_MISSING;
		}
		else{
			if(error){
				errorMessage.append(System.lineSeparator());	
				errorMessage.append(line);
			}
		}
	}
	scanner.close();
}
 
Example 5
Source File: QueryManager.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Find all prefixes declared in the query
 * @param queryString
 * @return
 */
protected static Set<String> findQueryPrefixes(String queryString) {
	
	Set<String> res = new HashSet<String>();
	
	Scanner sc = new Scanner(queryString);
	while (true) {
		while (sc.findInLine(prefixPattern)!=null) {
			MatchResult m = sc.match();
			res.add(m.group(1));
		}
		if (!sc.hasNextLine())
			break;
		sc.nextLine();
	}
	sc.close();
	return res;
}
 
Example 6
Source File: bug8015853.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        try {
            URL path = ClassLoader.getSystemResource("bug8015853.txt");
            File file = new File(path.toURI());
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                text += scanner.nextLine() + "\n";
            }
            scanner.close();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        text += text;

        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
 
Example 7
Source File: Utils.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static String getCopyright(File f) throws IOException {
    Scanner s = new Scanner(f, "ISO-8859-1");
    StringBuilder sb = new StringBuilder();
    while (s.hasNextLine()) {
        String ln = s.nextLine();
        sb.append(ln + "\n");
        // assume we have the copyright as the first comment
        if (ln.matches("^\\s\\*\\/$"))
            break;
    }
    s.close();
    return sb.toString();
}
 
Example 8
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Parses files like http://wiki.netbeans.org/NewProjectWizard Java Java
 * Application Java Desktop Application Java Class Library Java Project with
 * Existing Sources Java Free-form Project
 *
 * @param filename
 * @return
 */
public static ArrayList<String> parseFileByLines(File filename) {
    ArrayList<String> textLines = new ArrayList<String>();

    try {
        Scanner scanner = new Scanner(filename);
        while (scanner.hasNextLine()) {
            textLines.add(trimTextLine(scanner.nextLine()));
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
    }
    return textLines;
}
 
Example 9
Source File: JavaReadFile.java    From journaldev with MIT License 5 votes vote down vote up
private static void readUsingScanner(String fileName) throws IOException {
    Path path = Paths.get(fileName);
    Scanner scanner = new Scanner(path);
    //read line by line
    while(scanner.hasNextLine()){
        //process each line
        String line = scanner.nextLine();
    }
}
 
Example 10
Source File: ZoneTest.java    From iBioSim with Apache License 2.0 5 votes vote down vote up
/**
 * Reads in zones for testing.
 * @param zoneFile
 * 			The file containing the test zones.
 * @return
 * 			An array of zones for testing.
 * 			
 */
@SuppressWarnings("unused")
private static ZoneType[] readTestZones(File zoneFile)
{
	try {
		Scanner read = new Scanner(zoneFile);
		
		while(read.hasNextLine())
		{
			String line = read.nextLine();
			line.trim();
			
			if(line.equals("start"))
			{
				
			}
		}
		
		read.close();
		
	} catch (FileNotFoundException e) {
		e.printStackTrace();
		System.err.print("File not found.");
	}
	
	
	return null;
}
 
Example 11
Source File: AgilentCsvReadTask.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads meta information on the file. This must be called with the keys in order, as it does not
 * reset the scanner position after reading.
 * 
 * @param scanner The Scanner which is reading this AgilentCSV file.
 * @param key The key for the metadata to return the value of.
 */
private String getMetaData(Scanner scanner, String key) {
  String line = "";
  while (!line.trim().startsWith(key) && scanner.hasNextLine()) {
    line = scanner.nextLine();
    if (line.trim().startsWith(key))
      return line.split(",", 2)[1].trim();
  }
  return null;
}
 
Example 12
Source File: ExecuteScript.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<SearchResult> search(SearchContext context) {
    Collection<SearchResult> results = new ArrayList<>();

    String term = context.getSearchTerm();

    String scriptFile = context.getProperty(ScriptingComponentUtils.SCRIPT_FILE).evaluateAttributeExpressions().getValue();
    String script = context.getProperty(ScriptingComponentUtils.SCRIPT_BODY).getValue();

    if (StringUtils.isBlank(script)) {
        try {
            script = IOUtils.toString(new FileInputStream(scriptFile), "UTF-8");
        } catch (Exception e) {
            getLogger().error(String.format("Could not read from path %s", scriptFile), e);
            return results;
        }
    }

    Scanner scanner = new Scanner(script);
    int index = 1;

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (StringUtils.containsIgnoreCase(line, term)) {
            String text = String.format("Matched script at line %d: %s", index, line);
            results.add(new SearchResult.Builder().label(text).match(term).build());
        }
        index++;
    }

    return results;
}
 
Example 13
Source File: ChartPointsFormatterTest.java    From cucumber-performance with MIT License 5 votes vote down vote up
/**
 * Read a file
 * @param filepath The file path to the file.
 * @return String the file contents
 */
public static String readFile(String filepath)
{
	String result ="";
	try {
	 Scanner sc = new Scanner(new File(filepath)); 
	    while (sc.hasNextLine()) 
	      result+="\r\n"+sc.nextLine();
	    sc.close();
	} catch (Exception e) {
		return "";
	}
	return result;
}
 
Example 14
Source File: TestDFSAdmin.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private List<String> getReconfigureStatus(String nodeType, String address)
    throws IOException {
  ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(bufOut);
  ByteArrayOutputStream bufErr = new ByteArrayOutputStream();
  PrintStream err = new PrintStream(bufErr);
  admin.getReconfigurationStatus(nodeType, address, out, err);
  Scanner scanner = new Scanner(bufOut.toString());
  List<String> outputs = Lists.newArrayList();
  while (scanner.hasNextLine()) {
    outputs.add(scanner.nextLine());
  }
  return outputs;
}
 
Example 15
Source File: TestDFSAdmin.java    From big-c with Apache License 2.0 5 votes vote down vote up
private List<String> getReconfigureStatus(String nodeType, String address)
    throws IOException {
  ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(bufOut);
  ByteArrayOutputStream bufErr = new ByteArrayOutputStream();
  PrintStream err = new PrintStream(bufErr);
  admin.getReconfigurationStatus(nodeType, address, out, err);
  Scanner scanner = new Scanner(bufOut.toString());
  List<String> outputs = Lists.newArrayList();
  while (scanner.hasNextLine()) {
    outputs.add(scanner.nextLine());
  }
  return outputs;
}
 
Example 16
Source File: DateFormat.java    From jphp with Apache License 2.0 5 votes vote down vote up
private static int position(String str, Scanner scanner) {
    // return fast
    if (!scanner.hasNextLine()) {
        return str.length();
    }

    int res = 0;
    while (scanner.hasNextLine()) {
        res += scanner.nextLine().length();
    }

    return str.length() - res;
}
 
Example 17
Source File: ProjectPomUpdater.java    From spring-cloud-release-tools with Apache License 2.0 4 votes vote down vote up
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attr) {
	File file = path.toFile();
	if (POM_XML.equals(file.getName())) {
		if (pathIgnored(file)) {
			log.debug(
					"Ignoring file [{}] since it's on a list of patterns to ignore",
					file);
			return FileVisitResult.CONTINUE;
		}
		ModelWrapper model = this.pomUpdater.updateModel(this.rootPom, file,
				this.versionsFromBom);
		this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, file);
		if (this.assertVersions && !this.skipVersionAssert
				&& !this.pomUpdater.hasSkipDeployment(model.model)) {
			log.debug(
					"Update is a non-snapshot one. Checking if no snapshot versions remained in the pom");
			String text = asString(path);
			Scanner scanner = new Scanner(text);
			int lineNumber = 0;
			while (scanner.hasNextLine()) {
				String line = scanner.nextLine();
				lineNumber++;
				Pattern matchingPattern = this.unacceptableVersionPatterns
						.stream()
						.filter(pattern -> IGNORED_SNAPSHOT_LINE_PATTERNS.stream()
								.noneMatch(line::matches)
								&& pattern.matcher(line).matches())
						.findFirst().orElse(null);
				if (matchingPattern != null) {
					if (log.isDebugEnabled()) {
						log.debug("File text \n" + text);
					}
					throw new IllegalStateException("The file [" + path
							+ "] matches the [ " + matchingPattern.pattern()
							+ "] pattern in line number [" + lineNumber + "]\n\n"
							+ line);
				}
			}
			log.info("No invalid versions remained in the pom");
		}
	}
	return FileVisitResult.CONTINUE;
}
 
Example 18
Source File: FeedbackUtils.java    From android-uninstall-feedback with MIT License 4 votes vote down vote up
public static boolean cancel() {
    try {
        if (processId != 0) {
            android.os.Process.killProcess(processId);
        }
        //通过ps查找弹卸载反馈的进程
        String processName = context.getPackageName() + ":feedback";
        Process p = Runtime.getRuntime().exec("ps");
        p.waitFor();
        Scanner scanner = new Scanner(p.getInputStream());
        List<String> tags = new ArrayList<>();

        int pidRow = -1;
        while (scanner.hasNextLine()) {
            String scannerStr = scanner.nextLine();
            if (scannerStr.contains(processName) || scannerStr.toLowerCase().contains("pid")) {
                while (scannerStr.contains("  ")) {
                    scannerStr = scannerStr.replaceAll("  ", " ").trim();
                }
                String pidStr = null;
                int pid = -1;
                if (scannerStr.toLowerCase().contains("pid")) {
                    tags = Arrays.asList(scannerStr.toLowerCase().split(" "));
                    pidRow = tags.indexOf("pid");//pid所在的列号
                } else if (pidRow != -1){
                    pidStr = scannerStr.split(" ")[pidRow];
                    if (!TextUtils.isEmpty(pidStr)) {
                        pid = Integer.valueOf(pidStr);
                        android.os.Process.killProcess(pid);
                        Log.d("DaemonThread", scannerStr + "\npidRow:" + pidRow + ", kill pid:" + pid);
                    }
                }
            }
        }
        return true;
    } catch (Exception e) {
        Log.d("DaemonThread", "cancel Exception => " + e.getMessage());
        if (BuildConfig.DEBUG) {
            e.printStackTrace();
        }
    }
    return false;
}
 
Example 19
Source File: Server.java    From java-chat with MIT License 4 votes vote down vote up
public void run() {
  String message;

  // when there is a new message, broadcast to all
  Scanner sc = new Scanner(this.user.getInputStream());
  while (sc.hasNextLine()) {
    message = sc.nextLine();

    // smiley
    message = message.replace(":)", "<img src='http://4.bp.blogspot.com/-ZgtYQpXq0Yo/UZEDl_PJLhI/AAAAAAAADnk/2pgkDG-nlGs/s1600/facebook-smiley-face-for-comments.png'>");
    message = message.replace(":D", "<img src='http://2.bp.blogspot.com/-OsnLCK0vg6Y/UZD8pZha0NI/AAAAAAAADnY/sViYKsYof-w/s1600/big-smile-emoticon-for-facebook.png'>");
    message = message.replace(":d", "<img src='http://2.bp.blogspot.com/-OsnLCK0vg6Y/UZD8pZha0NI/AAAAAAAADnY/sViYKsYof-w/s1600/big-smile-emoticon-for-facebook.png'>");
    message = message.replace(":(", "<img src='http://2.bp.blogspot.com/-rnfZUujszZI/UZEFYJ269-I/AAAAAAAADnw/BbB-v_QWo1w/s1600/facebook-frown-emoticon.png'>");
    message = message.replace("-_-", "<img src='http://3.bp.blogspot.com/-wn2wPLAukW8/U1vy7Ol5aEI/AAAAAAAAGq0/f7C6-otIDY0/s1600/squinting-emoticon.png'>");
    message = message.replace(";)", "<img src='http://1.bp.blogspot.com/-lX5leyrnSb4/Tv5TjIVEKfI/AAAAAAAAAi0/GR6QxObL5kM/s400/wink%2Bemoticon.png'>");
    message = message.replace(":P", "<img src='http://4.bp.blogspot.com/-bTF2qiAqvi0/UZCuIO7xbOI/AAAAAAAADnI/GVx0hhhmM40/s1600/facebook-tongue-out-emoticon.png'>");
    message = message.replace(":p", "<img src='http://4.bp.blogspot.com/-bTF2qiAqvi0/UZCuIO7xbOI/AAAAAAAADnI/GVx0hhhmM40/s1600/facebook-tongue-out-emoticon.png'>");
    message = message.replace(":o", "<img src='http://1.bp.blogspot.com/-MB8OSM9zcmM/TvitChHcRRI/AAAAAAAAAiE/kdA6RbnbzFU/s400/surprised%2Bemoticon.png'>");
    message = message.replace(":O", "<img src='http://1.bp.blogspot.com/-MB8OSM9zcmM/TvitChHcRRI/AAAAAAAAAiE/kdA6RbnbzFU/s400/surprised%2Bemoticon.png'>");

    // Gestion des messages private
    if (message.charAt(0) == '@'){
      if(message.contains(" ")){
        System.out.println("private msg : " + message);
        int firstSpace = message.indexOf(" ");
        String userPrivate= message.substring(1, firstSpace);
        server.sendMessageToUser(
            message.substring(
              firstSpace+1, message.length()
              ), user, userPrivate
            );
      }

    // Gestion du changement
    }else if (message.charAt(0) == '#'){
      user.changeColor(message);
      // update color for all other users
      this.server.broadcastAllUsers();
    }else{
      // update user list
      server.broadcastMessages(message, user);
    }
  }
  // end of Thread
  server.removeUser(user);
  this.server.broadcastAllUsers();
  sc.close();
}
 
Example 20
Source File: YamlAssert.java    From picocli with Apache License 2.0 4 votes vote down vote up
public static void assertEqualCommand(String expected, String actual) {
        List<String> exceptions = Arrays.asList("userObject: ", "hasInitialValue: ", "initialValue: ", "# ");
        Scanner expectedScanner = new Scanner(expected);
        Scanner actualScanner = new Scanner(actual);
        int count = 0;
        NEXT_LINE: while (actualScanner.hasNextLine()) {
            String actualLine = actualScanner.nextLine();
            assertTrue("Unexpected actual line: " + actualLine + " in \n" + actual, expectedScanner.hasNextLine());
            String expectedLine = expectedScanner.nextLine();
            count++;

            String actLine = actualLine.trim();
            String expLine = expectedLine.trim();

            for (String exception : exceptions) {
                if (expLine.startsWith(exception) && actLine.startsWith(exception)) {
                    continue NEXT_LINE;
                }
            }
            if (expLine.startsWith("Mixin: ") && actLine.startsWith("Mixin: ")) {
                continue NEXT_LINE;
            }
            if (expLine.startsWith("paramLabel: '<arg") && actLine.startsWith("paramLabel: '<")) {
                continue NEXT_LINE;
            }

            if (expLine.startsWith("typeInfo: ") && actLine.startsWith("typeInfo: ")) {
                assertSimilarTypeInfo(expectedLine, actualLine);
//            } else if (expLine.startsWith("defaultValueProvider: ") && actLine.startsWith("defaultValueProvider: ")) {
//                assertSimilarDefaultValueProvider(expectedLine, actualLine);
//            } else if (expLine.startsWith("versionProvider: ") && actLine.startsWith("versionProvider: ")) {
//                assertSimilarVersionProvider(expectedLine, actualLine);
            } else if ((expLine.startsWith("getter: ") && actLine.startsWith("getter: ")) ||
                    (expLine.startsWith("setter: ") && actLine.startsWith("setter: "))) {
                assertSimilarGetterSetter(expectedLine, actualLine);
            } else {
                if (!expectedLine.equals(actualLine)) {
                    assertEquals("Difference at line " + count + ": expected ["
                                    + expLine + "] but was [" + actLine + "]",
                            expected, actual);
                }
            }
        }
        if (expectedScanner.hasNextLine()) {
            assertEquals("Actual is missing one or more lines after line " + count,
                    expected, actual);
        }
    }