Not getting the formatted text - android

I'm trying to read a .txt file. but in the textview the text in not formatted. i,e there is no new line in the textview even if i have given the new line. The sentences are continuous. Is it possible to format? the code goes like this
final StringBuffer buffer = new StringBuffer();
try{
DataInputStream dataIO= new DataInputStream(getResources().openRawResource(R.raw.chapter1));
String strLine= null;
while((strLine = dataIO.readLine())!=null){
buffer.append(strLine);
}
dataIO.close();
}catch(Exception e){
}
TextView tv=(TextView) findViewById(R.id.chapter);
tv.setText(buffer.toString());
}

Refer to the documentation of DataInputStream.readLine()
The string does not include the newline sequence.
So the strLine, which you are appending to the StringBuffer will not contain the newline.
You can modify your code as follows:
while((strLine = dataIO.readLine())!=null){
buffer.append(strLine);
buffer.append('\n');
}

Store your file content in a string after reading the file as follow ::
String fileContent = buffer.toString().replaceAll("\\r|\\n", "<br />");
Then, in your text view set text as HTML :
txtview.setText(Html.fromHtml(fileContent));

Related

Reading big string from file Android

So I was trying to read a text file of approx 40KB using Buffered Reader in android. The thing is one of the line (mostly last line) from the file exceeds 9000 characters which is difficult to store in String and to log it.
I tried this approach below but as characters exceed it discards parsing the remaining part from the line.
try {
File root = android.os.Environment.getExternalStorageDirectory();
File file = new File (root.getAbsolutePath() + "/" + "new.txt");
BufferedReader r = null;
r = new BufferedReader(new FileReader(file));
StringBuilder total = new StringBuilder();
String line;
while((line = r.readLine()) != null) {
Log.e("Line",line);
total.append(line);
}
r.close();
} catch (Exception e) {
e.printStackTrace();
}
To which I thought to change String line to String line = new String(new byte[1024*1024]) could solve my problem. But Android Studio is highlighting this as reductant code. The thing is I need to apply some regex stuff on each line in while loop.
Is there any workaround I can use. By the way here is my 40 KB file link https://www.dropbox.com/s/hp7vn6vt86adv6g/new.txt?dl=0
Edit: The file I am trying to parse is an html file.
Updated
I was wrong, the string in the line is not omitting the rest part as suggested by skandigraun (from comments). Logger was not printing the whole string because it was exceeding it's 4000 chars limit while my string was 8093 chars.
In short above code is working just as fine!

Can I remove the symbol new line from base 64 encoded key file?

I have a base 64 encoded key file. If I open it by Text Editor, I see 4 lines like this:
Then I copy the text and paste to Android Studio, I see the symbol "\n" is generated as below:
This pubic key doesn't work. So I tried :
Remove all "\n" symbol. Still doesn't work.
Replace the "\n" symbol with the space " ". Again doesn't work.
Could you please show me where I am wrong?
Rather than pasting the contents of the file into a string, why not just copy the file itself into your assets folder. For example:
public String readPublicKeyFromFile() {
String publicKeyString; = "";
try {
InputStream is = getAssets().open("public_key.txt");
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
return new String(buffer);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
Its android studio console character limitation that it shows long string in multiple lines.
Best way is to copy that string in any text editor(notepad) and make it single line string and then paste it to studio.
Another way is just delete that '\n' character from your string it will be single line string.
e.g.
private static final String = "abcdefgh" +
"ijklmnop" +
"qrstuvwxyz";
just remove '\n' character from your string.
If you creating the "publickey.txt" (base64) file, just use "Base64.NO_WRAP" flag for creating the file. This flag not allow the "\n" character.
By default it takes the "Base64.DEFAULT" flag, so every 64 characters after "\n" will be added automatically.
// for encoding the String with out \n
String base64Str=Base64.encode(your_string,Base64.NO_WRAP);
// for decoding
byte[] resByte=Base64.decode(base64Str,Base64.NO_WRAP);
// convert into String
String resStr=new String(resByte,"UTF-8");

Android: counting occurrence of words on file on SD Card

This should be straight forward but for some reason when I try to count words in a file after I download it to my SD Card, the number seems to be off. Also the more occurrences there are, the further my result seems to be off. I use Microsoft Word to verify the number of occurrences (using ignore case and whole word only). To test the number of occurrences, I use the "the_counter" variable below. I also verified there is nothing wrong with download & the FULL file is downloaded to my SD card. This is driving me nuts -- I'm thinking Word cannot be wrong here so what could possibly be wrong with my code below?
Could it be white space or special chars in the file causing the problem --is there a way to clean the file to verify this?
//Find the directory for the SD Card using the API
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,TEMP_FILE);
//Read text from file
//StringBuilder text = new StringBuilder();
m_tree = new Tree();
int i=0;
BufferedReader br = null;
long the_counter=0;
try {
br = new BufferedReader(new FileReader(file));
String line;
String []arLine;
while ((line = br.readLine()) != null) {
//get each word in line
if(line.length()==0)
continue;
arLine = line.split("\\s+");
//now add each word to search tree
for(i=0;i< arLine.length;++i){
m_tree.insert(arLine[i]);
if(arLine[i].equalsIgnoreCase("a"))
++the_counter;
}
}
m_sTest = Long.toString(the_counter) ;
br.close();
I edited my code to read in each character per line and create words manually. and I STILL GET THE SAME RESULT.
br = new BufferedReader(new FileReader(file));
String line;
String []arLine;
StringBuilder word = new StringBuilder();
while ((line = br.readLine()) != null) {
//check for word at end of last line
if(word.length()>0){
m_tree.insert(word.toString());
word.setLength(0);
}
char[] lineChars = new char [line.length()];
line.getChars(0,line.length(),lineChars,0);
for(char c: lineChars){
if(c== ' '){
//if we have a word then store and clear then move on
if(word.length()>0){
m_tree.insert(word.toString());
word.setLength(0);
}
}
else{
word.append(c);
}
}
This is issue was that I was not accounting for special characters in between words: i.e:
this-is-four-words and not one . I'm not even sure that is proper grammar or writing but it was in this file and it certainly threw off my count.

android separating a text file

I've been researching about how diablo 2 dynamically generates loot, and I thought it'd be fun to create a fun app that will randomly generate items using this system.
I currently have code which I believe should read the entire txt file, but it's not parsed.
It looks like:
private void itemGenerator() {
int ch;
StringBuffer strContent = new StringBuffer("");
InputStream fs = getResources().openRawResource(R.raw.treasureclass);
// read file until end and put into strContent
try {
while((ch = fs.read()) != -1){
strContent.append((char)ch);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
An example in the text file would look something like:
Treasure Class Item1 Item2 Item3
tc:armo3 Quilted_Armor Buckler Leather_Armor
tc:armo60a Embossed_Plate Sun_Spirit Fury_Visor
tc:armo60b Sacred_Rondache Mage_Plate Diadem
So what I'm thinking right now is putting each row into an array with StringTokenizer delimited by \n to get each row. Then somehow do it again with tab-delimited for each item in the array and put it into a 2D array?
I haven't coded it yet because I think there's a better way to implement this that I haven't been able to find, and was hoping for some helpful input on the matter.
For anyone actually interested in knowing how the item generation works, their wiki page, http://diablo2.diablowiki.net/Item_Generation_Tutorial, goes very in-depth!
I think you are facing problem in distinguishing between each lines that are read-out from file. In order to read the file line-by-line you should change your code as below:
InputStream fs = getResources().openRawResource(R.raw.treasureclass);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String line = null;
while((line = br.readLine()) != null){
Log.i("line", line);
//split the content of 'line' and save them in your desired way
}

Text file to useable text by TextView via class - Android

I have a text file in res/raw/stringtest.txt. On each line of this there are different lines of text that need to be put into individual TextViews.
Where can I find the java code to read the text file and then put it into textViews?
I believe you can use a FileInputStream to output the text to the Logcat but that is as far as I know so far. I know you put some code into the class files but I am unsure what it is to make it place the Text into the TextViews by id. Any information or code will be very appreciated.
I would use a BufferedReader, for its readLine method. Something like:
BufferedReader br = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.id.my_raw_file)));
String line = null;
while((line = br.readLine()) != null) {
// update TextView with string
}

Categories

Resources