Find an unicode character in a txt - android - android

I am reading a txt file containing unicode characters. I need to find whether a specific unicode character exist in this file. The code so far is as follows,
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("DistinctWords.txt"), "UTF-8"));
int i = 0;
String mLine = reader.readLine();
while ((mLine != null)) {
//process line
//unicode value taken from http://codepoints.net/U+0D85
if (mLine.contains("\u0D85")){
i++;
}
mLine = reader.readLine();
}
reader.close();
Log.i("tula", "Ayanna - " + String.valueOf(i));
} catch (IOException e) {
//log the exception
}
Problem: Value of "i" is always "0". When I open the same text file from notepad I can see the letter but my code fails to find it.

Like TronicZomB says, I think you need to be looking for the actual character, like:
while ((mLine != null)) {
//process line
if (mLine.contains("අ")){
i++;
}
mLine = reader.readLine();
}
You will want to use an editor that can handle the proper encoding:
Notepad on Windows will allow you to specify UTF-8 encoding on your file, but you have to set the encoding on the file to UTF-8 from ANSI.
On mac OS-x you can use TextEdit. In the preferences, with the open & save tab, you can set the document encoding.
On Linux StarOffice supposedly works, but I haven't used it.

Related

Reading a large text file with over 130000 line of text

How can i read a large text file into my Application?
This is my code but it does not work. My code must read a file called list.txt. The code worked only with a file with only 10.000 lines.
can someone helps me?
Thanks!
My code:(Worked with small files, but not with large files)
private void largefile(){
String strLine2="";
wwwdf2 = new StringBuffer();
InputStream fis2 = this.getResources().openRawResource(R.raw.list);
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis2));
if(fis2 != null) {
try {
LineNumberReader lnr = new LineNumberReader(br2);
String linenumber = String.valueOf(lnr);
while ((strLine2 = br2.readLine()) != null) {
wwwdf2.append(strLine2 + "\n");
}
// Toast.makeText(getApplicationContext(), linenumber, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), wwwdf2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Since you are processing a large file, you should process the data in chunks . Here your file reading is fine but then you keep adding all rows in string buffer and finally passing to Toast.makeText(). It creates a big foot-print in memory. Instead you can read 100-100 lines and call Toast.makeText() to process in chunks. One more thing, use string builder instead of string buffer go avoid unwanted overhead of synchronization. You initializing wwwdf2 variable inside the method but looks it is a instance variable which I think is not required. Declare it inside method to make it's scope shorter.

Load simple JSON file into 2 dimensional Array in Android

Driving myself crazy over the simplest thing. I have a JSON file called config.txt. The file is shown below.
{
"UsePipesInGuestData": true
}
All I want to do is get a 2 dimensional array such that:
Array[0] = UsePipesInGuestData and
Array[1] = true
I have been trying for 4 hours with various attempts, my most recent is shown below:
private void getConfig(){
//Function to read the config information from config.txt
FileInputStream is;
BufferedReader reader;
try {
final File configFile = new File(Environment.getExternalStorageDirectory().getPath() + "/guestlink/config.txt");
if (configFile.exists()) {
is = new FileInputStream(configFile);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
if(line!= null) {
line = line.replace("\"", ""); //Strip out Quotes
line = line.replace(" ", ""); //Strip out Spaces
if ((!line.equals("{")) || (!line.equals("}"))) {
} else {
String[] configValue = line.split(":");
switch (configValue[0]) {
case "UsePipesInGuestData":
if (configValue[1].equals("true")) {
sharedPreferences.edit().putString("UsePipes", "true").apply();
} else {
sharedPreferences.edit().putString("UsePipes", "false").apply();
}
break;
}
}
}
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I cannot seem to ignore the lines with the { and } in them.
Clearly there MUST be an easier way. JAVA just seems to take an extremely large amount of code to do the simplest thing. Any help is greatly appreciated.
I believe your condition is incorrect. You try to read the file in the else of the condition (!line.equals("{")) || (!line.equals("}")). Simplifying, your code will run when the following happens:
!(!{ || !}) => { && } (applying De Morgan's law)
This means you will only run your code when the line is "{" AND it is "}" which is a contradiction. Try using simple conditions, like (!line.equals("{")) && (!line.equals("}")) (this is when you want to execute your code).
Additionally, you may be getting end of line characters (\n) in your string, which will make your condition fail ("{\n" != "{"). I suggest you debug and see the actual values you're getting in those lines.

Storing multi color text using a file in android

I'm currently working on an android project which allows user to write text using different colors and store them for later use(i.e., editing or reading).
Is their any way to store a file in android with multi color text ??
NOTE: I googled out for the solution but can't find anything useful.
I'm guessing the user has to perform some action to switch color?
If so - you can use that trigger to store the text position/length when switching and save a list of text position - color.
A commenter suggested HTML, and that may be a good choice. You are welcome to try Html.fromHtml() to populate your EditText with the contents of a simple HTML-formatted file, and you are welcome to try Html.toHtml() to generate HTML from the contents of your EditText. However, historically, those methods were not written to do a good job of implementing a "round trip", meaning that the contents of the EditText may wind up changing from its starting point to what it contains after doing Html.toHtml() (to generate and save the HTML) and Html.fromHtml() (to populate the EditText with the previously-saved HTML). If they do not work, you can either fork that Html class and try to modify it as needed, or write your own code to take a Spanned object and convert it to/from HTML, by examining the spans and generating HTML tags from them.
PROBLEM SOLVED:
Code for storing a multi color text from EditText to a txt file:
protected void onDestroy() {
super.onDestroy();
boolean writing_allowed= ExternalStorageWriting.isWritingPossible();
if(writing_allowed)
{
String store= Html.toHtml(et.getEditableText());
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(store.getBytes());
fos.close();
} catch (Exception e) {
Toast.makeText(Notes.this, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
}
Code for reading that txt file and displaying it in EditText :
private void setNotes()
{
String myData="";
try {
File myExternalFile = new File(getExternalFilesDir(filepath), filename3);
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Spanned htmlText = Html.fromHtml(myData);
et.setText(htmlText);
}

Android - Comparing String Input On A Textfile Content

May I ask you to guide me how I can accomplish this problem?
I need to compare an inputWord to a string inside a .txt file and if found, return the whole line but if not, show "word not found".
Example:
inputWord: abacus
Text file content:
abaca - n. large herbaceous Asian plant of the banana family.
aback - adv. archaic towards or situated to the rear.
abacus - n. a frame with rows of wires or grooves along which beads are slid, used for calculating.
...
so on
Returns: abacus with its definition
What i am trying to do is compare my inputWord to the words before the " - " (hyphen as delimiter), if they dont match, move to the next line. If they match, copy the whole line.
I hope it doesnt seem like im asking you to "do my homework" but I tried tutorials around different forums and sites. I also read java docs but i really cannot put them together to accomplish this.
Thank you in advance!
UPDATE:
Here's my current code:
if(enhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
String delimiter = " - ";
String del[];
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (enhancedStem.equals(del[0]))
{
in.close();
databaseOutput.setText(s);
break;
}
}
in.close();
}
catch (FileNotFoundException e) {
databaseOutput.setText("" + e);
}
catch (IOException e1) {
databaseOutput.setText("" + e1);
}
}
Thanks a lot! Here's what I came up, and it returns the definition of inputs properly but the problem is, when i enter a word not found in the textfile, the app crashes. The catch phrase doesn't seem to work. Have any idea how I can trap it? Logcat says NullPointerExcepetion at line 4342 which is
s = in.readLine();
Assuming that the format of each line in the text file is uniform. This could be done in the following manner :
1) Read the file line by line.
2) Split each line based on the delimiter and collect the split String tokens in a temp String array.
3) The first entry in the temp token array will be the word before the "-" sign.
4) Compare the first entry in the temp array with the search string and return the entire line if there is a match.
Following code could be put up in a function to accomplish this :
String delimiter = "-";
String[] temp;
String searchString = "abacus";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null) {
String s = in.readLine();
temp = s.split(delimiter);
if(searchString.equals(temp[0])) {
in.close();
return s;
}
}
in.close();
return ("Word not found");
Hope this helps.
you may try like:
myreader = new BufferedReader(new FileReader(file));
String text = "MyInput Word";
while(!((text.equals(reader.readLine())).equals("0")));

Querying text file into database

My Program needs to be able to scan a text file, and store the values of the text file into a database.
Suppose I've read in a line of code that looks like this
3,95003,"ALLENDALE",,41.030902,-74.130957,2893
I want to be able to call a part of the string and store it as a database value. How exactly would I do that? I already know how to read in text files, but i need to know how to filter and only grab a part of them.
In a database I would usually add a value by doing something like this.
values.put("A", "B");
How can i read a value from only part of the textfile into B?
Say I want it to display values.put("A", "ALLENDALE").
Answer:
AgencyString = readText();
tv = (TextView) findViewById(R.id.letter);
tv.setText(readText());
StringTokenizer st = new StringTokenizer(AgencyString, ",");
while (st.hasMoreElements()) {
tv.setText(st.nextToken());
}
}
private String readText() {
InputStream inputStream = getResources().openRawResource(R.raw.agency);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
The next step for me is to store these values seperated into an array, and read them into my database. I was able to filter through my agency.txt file by using a StringTokenizer method and setting a 'comma' as my delimiter.
Look at. Use delimiters ",".
http://developer.android.com/reference/java/util/StringTokenizer.html
http://developer.android.com/reference/java/lang/String.html#split(java.lang.String)
http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String, int)

Categories

Resources