Hi I have a csv that looks like this:
r1c1|r1c2|r1c3
r2c1|r2c2|r2c3
As you can see it is delimited by the character "|"
In my application, I am trying to explode this using input stream. Here is my code:
String line = "";
String cvsSplitBy = "|";
try {
File initialFile = new File(myfile.txt);
InputStream targetStream = new FileInputStream(initialFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(targetStream));
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(cvsSplitBy);
String c0 = RowData[0];
String c1 = RowData[1];
String c2 = RowData[2];
Toast.makeText(mainactivity.this, c2, Toast.LENGTH_LONG).show();
}
}catch (IOException ex) {
// handle exception
}
Unfortunately, this appears to return each character in the csv as a row. The toast example above returns 1 then 2.
Any ideas how to return the proper column, anyone?
split() splits string around matches of the given regular expression, therefore use of special character (and vertical bar is one of these) requires escaping to strip its "powers".
String cvsSplitBy = "\\|"
See docs: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Related
I am reading a CSV file which have format: "col1"\t"col2". As my understanding there are two methods to read an CSV file and add to array.
1. ReadByLine.
2. ReadNext.
In Readbyline I face issue if col2 have \n in between the string, and that is added to my second index. like ("Hi how r u" "I am \n fine")
In readNext I face issue when my column1 is empty it return col2 value lile ("" "I am fine"). readNext return "I am fine".
Can any one suggest any best approach to work with this format.
Each line in a CSV file uses , as a delimiter. You should read the file line by line and split the line with the above delimiter:
try {
File f = new File("source.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
while( ( line = br.readLine() ) != null ) {
String[] tokens = line.split(",");
}
} catch (IOException e) {
e.printStackTrace();
}
Then, tokens.length will give you the size.
If you have spaces the use:
String newString = tokens[x].trim();
this is my first post! So if anything is wrong please tell me, i am new to android developing! Here is my question:
I am trying to generate HMAC-SHA1 with input is Hexstring for example the input key is "2cb1b780138bc273459232edda0e4b96" and input value is HexString too but way longer than the key, all the value and the key are Hexstring not character or normal string, so how can i achieve this? I searched a lot but all the result came to use the value and the key in normal string like "The quick brown fox jumps over the lazy dog"
I tried using convertHextoString code to change my HexString into Character string and put in the function like you did but the converted String from convertHextoString appear to have many SPECIAL CHARACTERS such as "\n" or ":" or "%" and so on and i think that is the problem why i got the wrong output. Here is my convertHextoString function
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
and the function to HMAC:
static String hash_hmac(String type, String value, String key) {
try { Log.i("Hien - value - hmac",value);
javax.crypto.Mac mac = javax.crypto.Mac.getInstance(type);
javax.crypto.spec.SecretKeySpec secret = new javax.crypto.spec.SecretKeySpec(key.getBytes(), type);
mac.init(secret);
byte[] digest = mac.doFinal(value.getBytes());
StringBuilder sb = new StringBuilder(digest.length*2);
String s;
for (byte b : digest){
s = Integer.toHexString(b & 0xff);
if(s.length() == 1) sb.append('0');
sb.append(s);
}
return sb.toString();} catch (Exception e) { android.util.Log.v("TAG","Exception ["+e.getMessage()+"]", e); } return ""; }
Please help!
In my android app
in message if i give message "hi #name,welcome your username:#username and password:#password" and in message #name,#username,#password are to be replaced with values iam reading from csv file
and it should send message as example:"hi praveen,welcome your username:neevarp and password:12345"
and those values are from csv .while searching i got some link
Named placeholders in string formatting
Map<String, String> values = new HashMap<String, String>();
values.put("value", x);
values.put("column", y);
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
but in android
StrSubstitutor
class is not there i think so is there any way to implement this
here is my code of reading values from csv and sending messages by replacing place holders
public void sendingSms(String message, String file_path) {
File file = new File("", file_path);
// Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int iteration = 0;
while ((line = br.readLine()) != null) {
if (iteration != 0) {
StringBuilder text = new StringBuilder();
text.append(line);
String[] contact = text.toString().split(",");
String phoneNumber = contact[4];
String name = contact[1];
String username = contact[2];
String password = contact[3];
//here i have to replace place holders with name,username,password values
//message.replace("#name", name);
//message.replace("#user", username);
Toast.makeText(Message.this, "" + message,
Toast.LENGTH_SHORT).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null,
null);
}
iteration++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
You should really be using the built in string formatting Android provides via string resources: http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
The functionality that you want is built right into the String class itself if you want to design your own StrSubstitutor class. Essentially building/designing a foreach with your Mapped values into the function.
String result = inputString.replace(valueString, replacedValueString);
But I am unaware of the function that you are requesting being built-in. Alex Fu as well has provided alternate means by which you could handle your string replacement.
Here I am reading file word by word and manipulating List view with these word. Problem here is First name and Last name are appearing in different rows. e.g. Name = "John Clerk" then I am getting "John" in first row and "Clerk" in second row of List view. They must be in single row and so forth for other data. What should I make changes to work it properly? My code...
String myData = "";
String strLine;
String listName = "" ;
FileOutputStream fos;
FileInputStream fstream;
DataInputStream in;
String[] SavedFiles;
BufferedReader br;
public void readFile(String file) throws IOException
{
fstream = openFileInput(file);
Scanner scanFile = new Scanner(new DataInputStream(fstream));
ArrayList<String> words = new ArrayList<String>();
String theWord, theWord1, theWord2;
while (scanFile.hasNext())
{
theWord = scanFile.next();
words.add(theWord);
}
Toast.makeText(getBaseContext(), "" + size, 1000).show();
adapterFriends = new ArrayAdapter<String>(getBaseContext(), R.layout.text, words);
lvFinal.setAdapter(adapterFriends);
adapterFriends.notifyDataSetChanged();
}
Try to use nextLine() instead of next(), as it should return every string between \n chars.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextLine()
hope that helps
If I understand correctly what you need, try this:
while (scanFile.hasNext())
{
String name = scanFile.next();
if (scanFile.hasNext())
{
name = String.format("%s %s", name, scanFile.next());
}
words.add(name);
}
I have a text file like this, separated by ";"
1022-3, 1603-4, 2012-5, 2489-6;
Gotta catch the first part before the "-" and pass to variable, and compare with milliseconds, if is equal the number, capture the number after of "-".
And do so with the next number after the semicolon, and so front.
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
And the beginning of the code to do what I need this here
private void LerArquivo() {
String lstrNomeArq;
File arq;
String lstrlinha;
long tempoInicio = 0;
long tempoDecorrido = 0;
try {
tempoDecorrido = (RecordSound.MilliSeconds() - tempoInicio);
lstrNomeArq = "/Android/data/br.com.couldsys.drumspro/cache/GravaSound.TXT";
String conteudotexto = "";
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
String capturaIndex = ("Conteudo do texto: "
+ conteudotexto.substring(
conteudotexto.indexOf("-") + 1,
conteudotexto.indexOf(";",
conteudotexto.lastIndexOf("-"))));
if (tempoDecorrido == capturatempo) {
DrumsProActivity.vsm.playSound(capturaindex);
// ler a nova linha
// se chegar ao final do string então para o while
if (conteudotexto.length() > 0) {
executar = false;
}
}
} catch (Exception e) {
trace("Erro : " + e.getMessage());
}
}
use this simpler code : create an array of substrings each contain a string formated ####-#
string[] MyStr = conteudotexto.split(',');
string sss= MyStr[0];
string sss2= MyStr[1];
....
now sss is 1022-3
sss2 is 1603-4 and so on ....
then reuse split function:
string[] MyStr2 = sss.split('-');
now we have :
MyStr2[0] = 1022
MyStr2[1] = 3
Maybe not particular elegant but just pragmatic for me - use the String split method. First split with ","
String[] parts = conteudotexto.split(",");
and then with each of the parts (here for the first)
String[] subParts = parts[0].split("-");
Just gives you everything in the pieces you need to look at and no danger get mixed up with positions etc.
What I need now is know how to catch part of text.
arq = new File(Environment.getExternalStorageDirectory(),
lstrNomeArq);
BufferedReader br = new BufferedReader(new FileReader(arq));
// pega o conteudo do arquivo texto
conteudotexto = br.readLine();
The text may vary more separation has two, the first number is separated from the second number by a "-" (dash) which is then separated by "," (comma)
549-8,1019-9,1404-3,1764-3,2208-10,2593-5,2938-9,3264-6,3700-0,4174-7,4585-8,4840-2,5192-9,5540-10,5932-0,
As has been shown
String[] parte1 = conteudotexto.split(",");
e em seguida
String[] parte2 = parte1[0].split("-");
The rule I'm trying to do is: Turn within a millisecond while the method and compare with the first part of the text
type
**If valor_milissegundos first part is equal to the number of text then
---> enters and runs the function playSound (the second number of the text);
------> goes to the next number in the text loop, capturing the second number of the text and compares it to the millisecond, if equal enters the IF block and catch the second number after the dash, and so on, until you reach the end of the text.**
Method return milliseconds calculates milliseconds
public static long MilliSeconds() {
// get Calendar instance
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}
I hope understand why I used the google translator
thank you