How to retrieve a specified data from a File? - android

I'm storing this data in a .dat file:
data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";
Every line has different values of date,y,value1 and value2.
I want to retrieve variable value1 of every line. How to browse the file and extract this variable of all lines. I'm stucking in this problem in my project. Thanks for helping.
EDIT: Example:
I have this 3 datas stored in the file:
11/09: 5.8L/100KM 20dt 250KM
12/09: 6.4L/100KM 60dt 600KM
13/09: 7.5L/100KM 50dt 543KM
In that case, i want to retrieve 20dt, 60dt and 50dt.

Here's one suggestion using regular expressions:
String line = "12/09: 6.4L/100KM 60dt 600KM";
Pattern p = Pattern.compile("(\\d+)dt");
Matcher m = p.matcher(line);
if (m.find())
System.out.println(m.group(1)); // prints 60
If you have several lines to iterate over, you'd use for instance a new BufferedReader(new FileReader("youfile.dat")) and do something like
String line;
while ((line = br.nextLine()) != null) {
Matcher m = p.matcher(line);
if (m.find())
process(m.group(1));
}
You could also just use line.split(" ") and select the 3:rd element:
String line = "12/09: 6.4L/100KM 60dt 600KM";
String dtVal = line.split(" ")[2];
// Optional: Remove the "dt" part.
dtVal = dtVal.substring(0, dtVal.length() - 2);
System.out.println(dtVal);

Related

SQL error 22008 with INSERT INTO

Hello I try to insert in sql
My code is:
archivo = new File("file name");
fr = new FileReader(archivo);
br = new BufferedReader(fr);
select = connection.createStatement();
statement = "INSERT INTO TABLE VALUES (";
cantidad = 0;
while(br.readLine() != null)
{
cantidad++;
}
br.close();
fr = new FileReader(archivo);
br = new BufferedReader(fr);
contador=0;
while((linea = br.readLine())!= null)
{
arrayString = linea.split("\\|");
for(int i = 0; i < arrayString.length; i++)
{
statement = statement + "'" + arrayString[i] + "',";
}
statement = statement.substring(0, statement.length() - 1) + ");";
select.executeUpdate(statement);
at the end before of select.executeUpdate(statement)
statement = INSERT INTO TABLE VALUES ('mx','mz','11','43','0','0','0','0','0','2015-01-19 09:24:20','0','10737','2015-01-19 09:24:20','20.71878','-103.45705','N','W','0.0','T','s','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','0.0','J1939','21','56','124','0','0','0');
then i receive the error SQL 22008
What is wrong?
Regards
The DateTime field format you have chosen is not acceptable.
2015-01-19 09:24:20
Try to convert to something like:
2015-01-19T09:24:20
Source on more formats:
http://msdn.microsoft.com/en-us/library/ms187819.aspx
It looks like your code is inserting some sort of tab or line break in the middle of your timestamps that you are trying to insert, that is making SQL Server throw an error that it didn't understand your format and tried to truncate/round the datetime value.
Try changing your code such that your datetime value are in the following format:
yyyy-mm-ddThh:mm:ss
For example:
2015-01-19T09:43:35

How to replace the word in the string by using replace in Android?

I want to replace one word in the String by using substring. But it seen didn't work.
for example: The string is 0000 , and I want to replace the first word from 0 to 1.
It should be 1000. but it doesn't.
The code is like the following
String WorkStatus = "0000";
if(WorkStatus.substring(0, 1).matches("0"))
{
WorkStatus.substring(0, 1).replace("0", "1");
Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}
It didn't work , the string always show 0000. And what I want is "1000"
Do I missing something ?
use this
String WorkStatus = "0000";
//You use matches, while you might as well use equals
if (WorkStatus.substring(0, 1).equals("0")) {
//reassign workstatus to workstatus where the first entry is a '1' + the last three chars "000"
WorkStatus = WorkStatus.substring(0, 1).replace("0", "1") + WorkStatus.substring(1, WorkStatus.length());
Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}
You didnt assign the modified string to WorkStatus
Another possibility is converting the string to a char[] and replacing the index, instead of working with substrings.
String WorkStatus = "0000";
char[] chars = WorkStatus.toCharArray();
if (chars[0] == '0') {
chars[0] = '1';
WorkStatus = new String(chars);
}
If you want other chars to become 1 instead of zero, alter the chars[0] into chars[index], where index is the index you want to change from 0 to 1
Or, even easier, use a StringBuilder:
int yourIndex = 2; //your index which you want to check for 0 and change to 1
StringBuilder sb = new StringBuilder("0000");
if (sb.charAt(yourIndex) == '0')
sb.setCharAt(yourIndex, '1');
WorkStatus = sb.toString();
method replace has a return value of the string after replaced
you shuold resign the result to the String
WorkStatus=WorkStatus.substring(0, 1).replace("0", "1")+ WorkStatus.substring(1, WorkStatus.length();
if you asign it to a new variable like the below code, you can get what you needed.
String newWorkStatus=WorkStatus.substring(0, 1).replace("0", "1")+WorkStatus.substring(1);
Log.d("LOG", "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d("LOG", "WorkStatus = " + WorkStatus + "\n");
Log.d("LOG", "New WorkStatus = " + newWorkStatus + "\n");
WorkStatus.substring(0, 1).replace("0", "1"); returns 1, you should use StringBuilder instead of String.
My solution:
StringBuilder WorkStatus = new StringBuilder("0000");
int pos = WorkStatus.indexOf("0", 0);
if (pos != -1) {
WorkStatus.replace(pos, pos + 1, "1");
}
System.out.print(WorkStatus);

How can I effectively replace one or more characters

I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);

java delimeter replacement for new line

Here is the scenario one input
String in = "<ENTER>title=Java-Samples<ENTER>" +
"<ENTER>author=Emiley J<ENTER>" +
"<ENTER>publisher=java-samples.com<ENTER>" +
"<ENTER>copyright=2007<ENTER>" +
"<ENTER>cool beans<ENTER>";
processs
in=in.substring(in.indexOf("<ENTER>")+7,in.lastIndexOf("<ENTER>"));
String[] mSplitted= in.replaceAll("<ENTER><ENTER>", "<ENTER>").split("<ENTER>");
String mFinal="";
for(int i=0;i<mSplitted.length;i++)
{
System.out.println("values: "+mSplitted[i]);
mFinal= mFinal+ mSplitted[i];
}
System.out.println(mFinal);
output is
title=Java-Samplesauthor=Emiley Jpublisher=java-samples.comcopyright=2007cool beans
Senario 2
input
String in = "What is the output of: <ENTER><ENTER>echo 6 % 4;";
processes
in=in.substring(in.indexOf("<ENTER>")+7,in.lastIndexOf("<ENTER>"));
String[] mSplitted= in.replaceAll("<ENTER><ENTER>", "<ENTER>").split("<ENTER>");
String mFinal="";
for(int i=0;i<mSplitted.length;i++)
{
// System.out.println("values: "+mSplitted[i]);
mFinal= mFinal+ mSplitted[i];
}
System.out.println(mFinal);
Output
nothing
I want the output to add a new line when is used
Still not 100% on your question but how about this:
String mFinal = in.replaceAll("<ENTER><ENTER>", "\n").replaceAll("<ENTER>", "");

How can I write a regular expression for this in android?

I am having a string(number) with special characters. I want to search for a sub-string(comprising of digits only) & also I want to detect the starting index & ending index of matching sub-string in the string.
For example: main string: (+91)-1231212 1231
Sub-string to search: 1212
Currently I am using the following code to do this but in place of 1212,it searched for 12312. For other cases, it works fine.
String sss0 = "1212";
String sss1 = "(+91)-1231212 1231";
sss0 = sss0.replaceAll("[^\\d]","");
System.out.println("*************************"+sss0);
String ptn = "" + sss0.charAt(0);
for(int jj=0; jj<sss0.length()-1; jj++){
ptn += "[^" + sss0.charAt(jj) + sss0.charAt(jj+1) + "]*?" + sss0.charAt(jj+1);
}
System.out.println("ptn: " + ptn);
Pattern p300 = Pattern.compile(ptn);
Matcher m300 = p300.matcher(sss1);
if(m300.find()){
System.out.println("start, stop: " + m300.start() + "," + (m300.end()-1 ));
System.out.println("substring: " + sss1.substring(m300.start(), m300.end()));
}
Please help me. Thanks in advance.
Try this :
int start = sss1.indexOf(sss0);
if(start != -1) {
System.out.println("Start : " + start);
System.out.println("End : " + start.length()); //maybe add +1 here depending on what you mean by end index.
}
You can also put this in a loop to find all occurences of the substring.
pseudocode:
pattern = ""
foreach char c in sss0:
pattern += c + "[^0-9]*"
found_substring = match(pattern, sss1)
the idea being to intersperse the literal characters you're looking for with the pattern that you're willing to skip over.

Categories

Resources