How do you read a .txt file in Android? - java

I am newbie in android development. Today for i was trying to display all my practiced programs of java in my application. I want the application to read the data written in .txt file.
In which folder should I store all my programs? They are more than 100.
I want to display the content of program 2 when I clicked the 2 on the list view or any other
Can we store the text files in database? If so how can I access them ? How can I read them?
Any basic ideas how can I solve this?

You can kept text file in raw / assets folder.
To read them just use this code.
From Assets:
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("YourTextFile.txt")));
From Raw:
InputStream inputStream = context.getResources().openRawResource(R.id.yourresoureid);
InputStreamReader inputreader = new InputStreamReader(inputStream)
as you are a java programmer no need to tell how to read data from InputStream, if your really want then tell me I will post the rest of the code.
Saving that huge amount of data in data base is not a good idea.
Example to read data from InputStream
BufferedInputStream bis=new BufferedInputStream(inputstream);
ByteArrayBuffer baf=new ByteArrayBuffer(1000);
while((k=bis.read())!=-1)
{
baf.append((byte)k);
}
String results=new String(baf.toByteArray());

Start with something easy and work up to the database option.
Yes, the answer would be quite long, and I think a tutorial on SQLite would be a place to start on this.
2,1. Try putting your text files in the assets folder and reading them like this. This code reads a file, and dumps it line by line into the log.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
AssetManager assetManager = getAssets();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
assetManager.open("hi.txt")));
// InputStream inputStream = assetManager.open("hi.txt");
// BufferedReader br = new BufferedReader(
// new InputStreamReader(inputStream));
String lineIn;
while ((lineIn = br.readLine()) != null) {
Log.d("ReadTheDamnFile", lineIn);
}
assetManager.close();
} catch (IOException e) {
}
}

try this its work fine :)
try
{
if(poslist==0)
{
in = this.getAssets().open("file1.txt");
iv.setBackgroundResource(R.drawable.fileimage1);
}
}
catch (IOException e)
{
e.printStackTrace();
}
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}
public void onClick(View v){
try {
line = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line != null){
tv.setText(line);
} else {
//you may want to close the file now since there's nothing more to be done here.
}

Related

Why are two try-catch blocks required for opening and reading a file?

I am trying to read a file but it is asking for two try-catch blocks, one for opening a file and another for reading its content. Why is this required?
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
while((line=reader.readLine())!=null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Consider using finally block for avoiding memory leaks and closing the streams if you are using versions before 7. From Java 7 on wards you can use try with resources is the best practice
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try-with-Resources:
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
try(BufferedReader reader = new BufferedReader(new FileReader(file));) {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Try java8, you will not require anything. You can simply do it like this.
import java.nio.file.Files;
import java.nio.file.Paths;
Files.lines(Paths.get(path))
.filter(l -> l.contains(searchWord)).forEach(System.out::println);
The try-catch block is required for IOException.
It will check for the contents available in the file. If there are no contents, then IOException would be thrown else the contents will be displayed.
It should be like:
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
while((line=reader.readLine())!=null)
{
System.out.println(line);
}
} catch(IOException ex)
{
System.out.println(ex.getMessage());
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Where is the folder for assets?

Simple Question I know - but my android app simply can´t find my CSV file. I´ve placed the file here:
and access it with this code:
public void getFragenfromCSV(){
AssetManager a = getAssets();
BufferedReader reader = null;
try {
InputStream is = a.open("fragenbronze.csv");
reader = new BufferedReader(new InputStreamReader(s));
} catch (IOException e) {
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
e.printStackTrace();
}
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
System.out.println(RowData[0]);
}
}
catch (IOException ex) {
// handle exception
}
}
On running the app I always get the IOException from the catch part.
you have to place it in
src/main/assets
never put something you want to keep in build/ as this get's removed with clean
Project Structure with assets folder
You are going inside build but actually you have to go inside src/main/assets.

Make text viewer read files faster in android

I have a simple text viewer class that opens text file and reads the strings. But the problem is, when the file is large >0.5Mb, opening takes quite a while. Is there a way to load small part first and then load all others or any other way to make this process faster ? Here is my code:
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
TextView txt = (TextView)findViewById(R.id.textView);
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null) {
try {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
txt.setText(buf.toString());
}
}

Read android system file

I have tried many solutions to read files but no one were working.
I need a method to read a system file and show the text in a toast or in a dialog.
Of course my app has root permission.
I have to show the content of "eoc_status" in a toast after a checkbox click.
For example;
Runtime.getRuntime().exec("/sys/kernel/abb-chargalg/eoc_status").getInputStream();
I need to open text files.
Assuming you do have read-access to eoc_status
You are going to want to read it, not exec it. ie use cat or use a FileReader:
Then you will want to do something (put it in your toast) with the returned InputStream.
For example:
BufferedReader buffered_reader=null;
try
{
//InputStream istream = Runtime.getRuntime().exec("cat /sys/kernel/abb-chargalg/eoc_status").getInputStream();
//InputStreamReader istream_reader = new InputStreamReader(istream);
//buffered_reader = new BufferedReader(istream_reader);
buffered_reader = new BufferedReader(new FileReader("/sys/kernel/abb-chargalg/eoc_status"));
String line;
while ((line = buffered_reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
// TODO
e.printStackTrace();
}
finally
{
try
{
if (buffered_reader != null)
buffered_reader.close();
}
catch (IOException ex)
{
// TODO
ex.printStackTrace();
}
}

Skip execution if exception thrown

I am stuck on something very basic. In our game we have a leveleditor/loader that can fetch levels via URL. Now if the URL points to a nonexistant file the editor should refuse to load the level and simply stay in its currentlevel, I am just struggling with the basic code.
private void loadLevel(URL url) {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
readLine(in);
in.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Essentially, if FileNotFound is thrown (or any other) readLine(in) should NOT proceed. All kinds of NPE if it does.
private void loadLevel(URL url) {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
/*if(in!=null){
readLine(in);
in.close();
}*/
readLine(in);
in.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT: After #LuiggiMendoza's suggestion.
Use throws and finally. Let the calling function handle it. I haven't tested it, but this sort of thing is the idea...
private void loadLevel(URL url) throws IOException, FileNotFoundException {
Scanner in = null;
try {
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));
if (in == null) throw new FileNotFoundException();
readLine(in);
}
finally {
in.close();
}
}
On the context of one single thread, if this line below throws exception, the next line of code will not execute. If you think your code is doing otherwise, it might be another thread doing it / some other code
in = new Scanner(new BufferedReader(new InputStreamReader(
url.openStream())));

Categories

Resources