Reading specific part from txt file is not working - android

This is my code:
File root = Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Bonbon info");
dir.mkdirs();
File f = new File(dir, "paket.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
br.skip(60);
int charactersRead = 0;
while ((line = br.readLine()) != null && charactersRead < 12) {
text.append(line);
text.append('\n');
charactersRead++;
}
}
catch (IOException e) {
}
final String URL = text.toString();
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText(text);
Reading is working, but i can't read only 12 characters, it reads trough the end of file, don't know why.

I'm guessing your file is relatively short.
You're calling BufferedReader.readLine(), which in an attempt to be efficient is sucking up a big chunk of the file stream rather than going through it character-by-character.
If you want that finer control over what you read, it's probably worth using an InputStream implementation straight up.

Related

How do I insert new line in EditText field while reading the text from a file

I am trying to create an android app in which it will take the contents of the file which is in assets, copy the contents to the file in filestorage. Then while displaying, it will read the file in filestorage and will append the lines in edittext.
The problem i am facing is empty lines are not being read.
Following is the code snippet in which i am reading the contents of asset file and copying it in file "current.txt" which will be stored in filestorage.
reader = new BufferedReader(new InputStreamReader(getAssets().open("pravachan.txt")));
ContextWrapper contextWrapper=new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir("FileStorage",Context.MODE_PRIVATE);
File myInternalFile=new File(directory,"current.txt");
FileWriter filewriter = new FileWriter(myInternalFile);
BufferedWriter out = new BufferedWriter(filewriter);
String mLine = reader.readLine();
while (mLine != null)
{
//process line
if(mLine.isEmpty())
{
out.write(" ");
String str = System.getProperty("line.separator");
out.write(str);
}
else
out.write(mLine);
mLine = reader.readLine();
}
out.close();
Following is the code snippet in which i am appending the edittext with contents of "current.txt" file
ContextWrapper contextWrapper=new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir("FileStorage", Context.MODE_PRIVATE);
File myInternalFile=new File(directory,"current.txt");
FileInputStream fis=new FileInputStream(myInternalFile);
BufferedReader reader=new BufferedReader(new InputStreamReader(fis));
String mLine = reader.readLine();
TextView tv = (TextView)findViewById(R.id.editText);
while(mLine != null)
{
if(mLine.isEmpty()) {
tv.append(" ");
String str = System.getProperty("line.separator");
tv.append(str);
}
else
tv.append(mLine);
mLine = reader.readLine();
}
I don't want empty lines to be skipped.I want the file as it is to be displayed in Edittext. Please Help. Thanks in advance!
I got the answer!
Instead of doing out.write(str) in which str is the line separator, I did out.newline(). It worked!

Storing txt files

I'm working on a sort of a magazine app which contains a lot of txt files which I read the text from (only read not write) , And I'm a little bit confused , I have read the documentation about file storage but still don't seem to get the right way to store my txt files. Should those files be in the the Assets? Is it possible to have a folders inside the assets? And if yes how can I acsses these folders?
res/raw will be a good place to put them. If you placed a text file named "article.txt" in the raw resource folder, you would start by putting the file into an InputStream like this (note that "ctx" is a Context which an Activity inherits from):
InputStream inputStream = ctx.getResources().openRawResource(R.raw.article);
Then you turn the InputStream into a String. This can be done about 1000 different ways. Here's one way:
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
String fileContentsStr = text.toString();
Here is a fully working method (using the above conversion technique) to turn a text file from the raw folder into a string. Which I got from this post Android read text raw resource file.
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
Using "article.txt" still, you would call this method from an Activity like so:
readRawTextFile(this, R.raw.article);

Why am I getting multiple results for the same string, and why are they different

Im looping through a SDCard directory, reading the text in each file, and writing the text to dynamically added textViews.
Each file contains line breaks, I think that it where the problem lies.
I've searched SO, and Google, tried some suggestions, and now my code returns and prints each text file twice. The first only contains the text until the first line break, the ssecond prints the text exactly how I need it.
Example text file test.txt
This is a test.
And I cannot make it work
The desired output is
test.txt
This is a test.
And I cannot make it work
The first time the views are added I get
test.txt
This is a test.
The second time, I get the desired output. It does this with all txt files
Here is my code
String sdcard = Environment.getExternalStorageDirectory() + "/.BELIEVE/PushMessages/";
// go to your directory
File fileList = new File( sdcard );
//check if dir is not null
if (fileList != null){
// so we can list all files
File[] filenames = fileList.listFiles();
// loop through each file
for (File tmpf : filenames){
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(tmpf));
String name = tmpf.getName();
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
TextView title = new TextView(PushMessagesPage.this);
TextView message = new TextView(PushMessagesPage.this);
ll.addView(title);
title.setLayoutParams(textViewParams);
title.setTextAppearance(this, android.R.attr.textAppearanceLarge);
title.setTextColor(0xff33b5e5);
title.setText(name);
ll.addView(message);
message.setLayoutParams(textViewParams);
message.setTextColor(0xffffffff);
message.setText(text);
What is wrong with this code?
Your code should be like this.
for (File tmpf : filenames) {
StringBuilder text = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(tmpf));
String name = tmpf.getName();
String line;
TextView title = new TextView(StackDemosActivity.this);
ll.addView(title);
title.setLayoutParams(textViewParams);
title.setTextAppearance(this,
android.R.attr.textAppearanceLarge);
title.setTextColor(0xff33b5e5);
title.setText(name);
TextView message = new TextView(StackDemosActivity.this);
ll.addView(message);
message.setLayoutParams(textViewParams);
message.setTextColor(0xffffffff);
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
message.setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}

Problems reading text from file

I'm trying to read some text from a .txt file, here's my code:
String filePath = bundle.getString("filepath");
StringBuilder st = new StringBuilder();
try {
File sd = Environment.getExternalStorageDirectory();
File f = new File(sd, filePath);
FileInputStream fileis = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(
fileis));
String line = new String();
while ((line = buf.readLine()) != null) {
st.append(line);
st.append('\n');
}
Log.i("egor", "reading finished, line is " + line);
} catch (FileNotFoundException e) {
Log.i("egor", "file not found");
} catch (IOException e) {
Log.i("egor", "io exception");
}
reader.setText(st.toString());
The text looks like this:
This is a sample text to test
The .txt file is created in Windows notepad.
And here's what I'm getting:
What's wrong with my code? Thanks in advance.
Is the file in utf-8 (unicode) format? For some reason, Notepad always adds a byte-order mark to unicode files, even when the byte-order is irrelevant. When interpreted as ASCII or ANSI, the BOM will be seen as several characters. It's possible this is what's causing your problem.
If so, the solution is to use a more competent text editor than Notepad, or write code that checks for a BOM first in all unicode files.
If none of this makes sense to you, try googling 'unicode' and 'byte-order mark'.
Wrap a FileReader object in the BufferedReader object instead.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html
File sd = Environment.getExternalStorageDirectory();
File file = new File(sd, filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
st.append(line);
st.append("\n");
}
br.close();
Try with the folowing code
File f = new File(str);
FileInputStream fis = new FileInputStream(f);
byte[] mydata1 = new byte[(int) f.length()];
fis.read(mydata1);
System.out.println("...data present in 11file..."+new String(mydata1));

Character count from a text file

i am trying to count the number characters in a text file which i have retrieved the SD card need some advice here am new to android programming
using this code to retrieve the text file from the sd card
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.TextView01);
//Set the text
tv.setText(text);
Assuming that you have already opened the file and haven't encountered any exceptions in it, I would suggest using this, instead of what you're using:
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line="";
int c,counter=0;
while ((c = br.read()) != -1) {
line+=(char)c;
counter++;
}
text.append(line);
}
catch (IOException e) {
//You'll need to add proper error handling here
}
Here, I haven't used text.append("\n") because your file will already be having line break characters.
In the enc counter will be having the text count, including spaces and special characters like '\n'

Categories

Resources