Following function will parse string resp
, which will be like shown in following example. I will get an IP address in the form of a hexadecimal string like "C0A2AA32" and I need to convert that string and save it to a file.
Example of resp
: "This is just a string with ip="2342A022" now I need to parse it"
void WritePublicIPAddressToFile(String resp)
{
//find string in response
String stringToFind = "ip=";
//get index of stringToFind
int indexOfIP = resp.indexOf(stringToFind);
String newString = "";
//find exact ip address which will be after = in stringToFind
for(int i = indexOfIP; i<resp.length(); i++)
{
while(resp.charAt(i++) != '\"');
while(resp.charAt(i) != '\"')
{
newString += resp.charAt(i++);
}
break;
}
int lenNewString = newString.length();
String newIPAddress = "";
//get two bytes from hex string and convert to ipaddress
if(lenNewString == 8) //lenth of ipaddress raw data should be 8
{
long l;
for(int i = 0;i<lenNewString;i+=2)
{
l = Long.parseLong(String.format("%c%c", newString.charAt(i),newString.charAt(i+1)),16);
newIPAddress += String.format("%d.", l);
}
}
StringBuilder sb = new StringBuilder(newIPAddress);
sb.deleteCharAt(sb.length() - 1);//remvoe last '.' in ipaddress
//final ipaddress to save in file
newIPAddress = stringToFind + "\"" + sb.toString() + "\"";
//write IP Address to file
File file = new File("SomeFilePath.txt");
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
fileWriter.write(newIPAddress);
fileWriter.flush();
fileWriter.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}