Compare a string to CMD output using Java - java

I'm trying to create a method that returns true or false based off of the result from sfc /scannow but for some reason the string comparison always returns false even though it prints as exactly what I'm comparing it to. Any ideas?
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "sfc /scannow");
builder.redirectErrorStream(true);
Process p = builder.start();
Scanner sn = new Scanner(new InputStreamReader(p.getInputStream()));
while (sn.hasNextLine()) {
String line = sn.nextLine();
System.out.println(line);
if(line.equalsIgnoreCase("Windows Resource Protection did not find any integrity violations.")) {
isHealthy = true;
break;
}
}
if(isHealthy == true) {
return true;
}
else if(isHealthy == false) {
return false;
}

In this case your are comparing Objects and not always the value itself, so you'll be good checking using contentEquals:
...
if(line.contentEquals("What Do you want to verify")) { condition }
Let me know if this works for you!
The String#equals() not only compares the String's contents, but also checks if the other object is also an instance of a String . The String#contentEquals() only compares the contents (the character sequence) and does not check if the other object is also an instance of String

Related

always return false when compare an existing string from a test file to the newly enterer object with parameter

This is my method for checking if the first three elements are the same
carModel is a string
purchasePrice is a double
purchaseDate is a Date
I stored these in a txt file, separating with a comma and a space like ", "
However, this method always returns false,even if i input just the same record. But when I changed the first"&&" into "||", it would return true.
public static boolean exist(Car c) {
String line = "";
File file = new File("Car Records.txt");
try {
BufferedReader fr = new BufferedReader(new FileReader(file));
while ((line = fr.readLine()) != null) {
String[] s = line.split(", ");
if ((s[0].equals(c.carModel)) &&(s[1].equals(c.purchasePrice))&& (s[2].equals(c.purchaseDate))
&& (s[5].equals(false)) ){
return true;
}
}
fr.close();
} catch (IOException e) {
System.out.println("Error reading file");
}
return false;
}
s[0],s[1] and s[2] are Strings, so comparing them to double or to Date will never return true.
You'll have to parse the input Strings into the correct type before making the comparison.
You'll need something like this (I didn't fix the Date comparison, since I don't know how you represent the date in your input file):
if ((s[0].equals(c.carModel)) &&(Double.parseDouble(s[1])==c.purchasePrice)&& (s[2].equals(c.purchaseDate))
&& (s[5].equals("false")) ){
return true;
}

different results for same method call [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i do have a class CheckPrograminstallation(which is part of a eclipse plugin), with a method check, which checks whether a program is installed. It return true when installed and false otherwise.
public class CheckPrograminstallation{
public static boolean check(String programname, String OsName)
throws Exception {
// Get installation path of programname
String foundpath = "";
String dirName = "";
String line;
String programpath = null;
Process process = null;
boolean IsInstalled = false;
if (OsName.equals("Windows")) {
try {
// get Windows Directory first
process = Runtime.getRuntime().exec("cmd /c echo %windir%");
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
// read from stream
if ((line = reader.readLine()) != null) {
foundpath = line.toString();
// cut off "\Windows" from the found path
int last = foundpath.lastIndexOf("\\");
dirName = foundpath.subSequence(0, last).toString();
process = null;
// get program installation path
process = Runtime.getRuntime().exec(
"cmd /c where /R " + dirName + " " + programname);
reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
if ((line = reader.readLine()) != null) {
programpath = line.toString();
System.out.println(programpath);
IsInstalled = true;
}
}
} catch (Exception e) {
DO SOMETHING);
}
}
When i call the method from a test class, it works.
But when i call the same method while running the Plugin:
...boolean isInstalledPscp;
boolean IsWindows;
...
if (IsWindows == true) {
// for Windows: check if pscp is installed
isInstalledPscp = CheckIfInstalled.check("pscp", "Windows");
if (isInstalledPscp == false) {
do something }
}
...it always returns false.
How can that be?
This has been driving me crazy for a whole day. Using .equals for String comparison, and still getting false as result. So this is not a string comparison problem IMHO.
Change your string comparison from:
if (OsName == "Windows") {
To:
if (OsName.equals("Windows")) {
Since your if doesn't succeed, it never goes into if and hence it returns your false.
You compare strings using the equals() method and not logical equals operator ==
I also recommend that you follow java naming conventions and use variables names starting with lower case letters such as osName instead of OsName.
Print out what are the paths that are returned inside your code (if any), I suspect that from within the plugin the runtime parameters are different.
Also maybe System.getEnv System.getProperties is a better way to find windows dir than starting a new process.

Java comparing lines in file with String

I'm experiencing an strange issue with a file in Java...
I want to compare every line of this file with a string (host variable), but (I don't know why), the while loop is always comparing the first line of the file and ignores the second line, the third...
Here's the code:
fr = new FileReader (file);
inf = new BufferedReader(fr);
String l;
while ((l=inf.readLine()) != null) {
if (host.contains(l))
return true;
else
return false;
}
Any help would be appreciated...
Two problems:
You are finding the line in the host name - that's like finding a haystack in a needle - reverse the test
No matter the result of the condition, you return after testing it just once, so only the first line is tested
Instead, try this:
String l;
while ((l=inf.readLine()) != null)
if (l.contains(host))
return true;
return false;
It should be host.equals(l), or possibly l.contains(host). It depends what you want to do.
It's only testing the first line in your file because of the if/else statement in the loop. Either branch results in a return thus stopping the rest of the file's contents from being processed.
Maybe you should return false only after you've reached the end of your file?
fr = new FileReader (file);
inf = new BufferedReader(fr);
String l;
while((l=inf.readLine())!=null){
if (host.contains(l))
return true;
}
return false;
Suppose you are looking for the host string in the file. You could possible do it like this.
public boolean contains(Reader in, String word) throws IOException {
BufferedReader inf = new BufferedReader(in);
String l;
boolean found = false;
while((l=inf.readLine())!=null){
if (l.contains(word)) {
found = true;
break;
}
}
return found;
}

Begin the reading of a file from a specific line

i have a file similaire to this :
...
The hotspot server JVM has specific code-path optimizations
# which yield an approximate 10% gain over the client version.
export CATALINA_OPTS="$CATALINA_OPTS -server"
#############HDK1001#############
# Disable remote (distributed) garbage collection by Java clients
# and remove ability for applications to call explicit GC collection
export CATALINA_OPTS="$CATALINA_OPTS -XX:+DisableExplicitGC"
# Check for application specific parameters at startup
if [ -r "$CATALINA_BASE/bin/appenv.sh" ]; then
. "$CATALINA_BASE/bin/appenv.sh"
fi
#############HDK7564#############
# Disable remote (distributed) garbage collection by Java clients
# and remove ability for applications to call explicit GC collection
export CATALINA_OPTS="$CATALINA_OPTS -XX:+DisableExplicitGC"
i want to begin the reading from the line where exists the word "HDK1001" and end it where the world "HDK7564"
i tryed with this code but i am unable to do the limitation
public static HashMap<String, String> getEnvVariables(String scriptFile,String config) {
HashMap<String, String> vars = new HashMap<String, String>();
try {
FileInputStream fstream = new FileInputStream(scriptFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String var= "HDK1001";
while ((strLine = br.readLine()) != null ) {
if (strLine.startsWith("export") && !strLine.contains("$")) {
strLine = strLine.substring(7);
Scanner scanner = new Scanner(strLine);
scanner.useDelimiter("=");
if (scanner.hasNext()) {
String name = scanner.next();
String value = scanner.next();
System.out.println(name+"="+value);
vars.put(name, value);
}
}
Help me please
try this code.
public static HashMap<String, String> getEnvVariables(String scriptFile,
String config) {
HashMap<String, String> vars = new HashMap<String, String>();
BufferedReader br = null;
try {
FileInputStream fstream = new FileInputStream(scriptFile);
br = new BufferedReader(new InputStreamReader(fstream));
String strLine = null;
String stopvar = "HDK7564";
String startvar = "HDK1001";
String keyword = "export";
do {
if (strLine != null && strLine.contains(startvar)) {
if (strLine.contains(stopvar)) {
return vars;
}
while (strLine != null && !strLine.contains(stopvar)) {
strLine = br.readLine();
if (strLine.startsWith(keyword)) {
strLine = strLine.substring(keyword.length())
.trim();
String[] split = strLine.split("=");
String name = split[0];
String value = split[1];
System.out.println(name + "=" + value);
vars.put(name, value);
}
}
}
} while ((strLine = br.readLine()) != null);
} catch (Exception e) {
e.printStackTrace();
}
return vars;
}
Your example code is quite far off, and I don't intend to rewrite all of your code, I will give you some pointers though. You are already doing:
if (strLine.startsWith("export") && !strLine.contains("$"))
This is your conditional that should be testing for the "HDK1001" string instead of whatever it's doing right now. I'm not sure why you are checking for the word "export" when it seems like it doesn't matter for your program.
There isn't a way to just magically start and end at specific words in the file, you MUST start at the beginning and go line by line checking all of them until you find your desired first and last line. Once you find that first line, you can continue reading until you reach your desired end line and then bail out.
this is pseudo code that follows the kind of logic you would want to be able to accomplish this task.
flag = false
inside a loop
{
read in a line
if( line != #############HDK1001############# && flag == false){ //check to see if you found your starting place
nothing useful here. lets go around the loop and try again
else // if i found it, set a flag to true
flag = true;
if( flag == true) // am i after my starting place but before my end place?
{
if( line == #############HDK1001#############)
do nothing and go back through the loop, this line is not useful to us
else if( line == #############HDK7564#############) //did i find my end place?
flag = false // yes i did, so lets not be able to assign stuff any more
else // im not at the start, im not at the end. I must be inbetwee. lets read the data and assign it.
read in the lines and assign it to variables that you want
}

Search string in file and return next line (in Java)

As my title says. I need to search through a file for a string. When its found, I need the next line.
It's a file like this:
hello
world
When "hello" is found, "world" needs to be returned.
File file = new File("testfile");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (scanner != null) {
String line;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line == "hello") {
line = scanner.nextLine();
System.out.println(line);
}
}
}
It reads through the file but it doesn't find the word "hello".
if (line == "hello") {
should be
if ("hello".equals(line)) {
You have to use equals() method to check if two string objects are equal. == operator in case of String(and all objects) only checks if two reference variables refer to the same object.
if (line == "hello")
should be changed to
if (line.contains("hello"))
Instead of using == operator to compare two strings use
if(line.compareTo("hello") == 0)

Categories

Resources