Escolar Documentos
Profissional Documentos
Cultura Documentos
up vote54down votefavorite
22
I am new to Android development.
I need to read a text file from the SD card and display that text file. Is there
any way to view a text file directly in Android or else how can I read and disp
lay the contents of a text file?
android android-sdcard
shareimprove this question
edited Jul 1 '11 at 8:07
Miuranga
1,03672954
asked May 25 '10 at 7:12
RSSS
321245
do you want to know how to write a program that reads a txt file or do y
ou want to know how to do it as a user? SteelBytes May 25 '10 at 7:28
add a comment
4 Answers
activeoldestvotes
up vote113down vote
In your layout you'll need something to display the text
. A TextView is the obvious choice. So you'll have something like this:
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
And your code will look like this:
//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');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
This could go in the onCreate() method of your Activity, or somewhere else depen
ding on just what it is you want to do.
shareimprove this answer
edited May 13 '14 at 10:11
AlvaroSantisteban
1,84431938
answered May 25 '10 at 9:27
Dave Webb
127k40253269
1
@Android Developer - In the sample code it says "You'll need to add prop
er error handling here". Did you do that because that's probably the mostly like
place you'll find your problem. Dave Webb Jul 21 '11 at 15:01
@Dave Webb sorry for the not update my comment. it works for me also. Ac
tually when i put the file in the DDMS then it will clear all the data from the
file thats why it returns null at my end.
Amit Thaper Jul 22 '11 at 4:04
Will this work using a shared network file? I want to file a file in a s
hared file over the internet, the would the file directory look like, "192.168.1
97.84/hdd1", "ActivityLog.txt" Michael Zeuner Jul 23 '12 at 13:41
1
@DaveWebb: you should also add uses permission : READ_EXTERNAL_STORAGE i
n your manifest file Houcine Mar 15 '13 at 12:35
show 1 more comment
up vote5down vote
In response to
Don't hardcode /sdcard/
Sometimes we HAVE TO hardcode it as in some phone models the API method returns
the internal phone memory.
Known types: HTC One X and Samsung S3.
Environment.getExternalStorageDirectory().getAbsolutePath() gives a different pa
th - Android
shareimprove this answer
answered Jun 21 '13 at 6:16
Sibbs Gambling
3,4421047107
up vote0down vote
package com.example.readfilefromexternalresource;
import
import
import
import
import
java.io.BufferedReader;
java.io.File;
java.io.FileNotFoundException;
java.io.FileReader;
java.io.IOException;
import
import
import
import
import
import
import
import
import
import
import
import
import
android.app.Activity;
android.app.ActionBar;
android.app.Fragment;
android.os.Bundle;
android.os.Environment;
android.view.LayoutInflater;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.view.ViewGroup;
android.widget.TextView;
android.widget.Toast;
android.os.Build;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
shareimprove this answer
answered Aug 7 '14 at 6:04
vikseln
41438
add a comment
up vote0down vote
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file na
me>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
shareimprove this answer
answered May 13 '15 at 11:11
RSH
135
Can you provide an explanation to your code please.. like where to use i
t, why does that do the job, etc.
Soma May 13 '15 at 11:32
add a comment
0 0 3
Each android device supports external storage (SD card) which can be used direct
ly by user to save multimedia content as well as by an app to save it's data. Si
nce the Internal storage of a device is very limited so it becomes a necessity f
or an app to transfer the large files to SD card.
Downloading Files in Android:
In Android version 2.3 Gingerbread (API level 9), a new service was added to and
roid OS "DownloadManager"specially for the purpose of downloading files througho
ut HTTP requests. It automatically manages the Progress bar in Notification, lar
ge sized Files, Retry Download if fail or even after the device reboots. So, cur
rently it's the best solution for downloading files. Below are the steps to crea
te a simple application for testing purpose:
1. Create a new Android project in Eclipse.
2. Select Blank Activity.
3. In Activity_main.xml file, Place the below code.
a.) One button to start downloading a file throughout internet.
b.) Another button to Generate the list of files present in app directory.
c.) Edit Text to display the list of files in app directory.
4. In your MainActivity.java file, paste the below code in OnCreate method of Ac
tivity
5. Paste the below two functions in same MainActivity class.
a) isDownloadManagerAvailable Function queries and returns a boolean indicating
whether the Download Manager Service for device's OS version or not (not availab
le in Android version less than 2.3).
b) IF the above function returns TRUE, only then we can use the downloadFile met
hod.
c) downloadFile function makes use of the DownloadManager manager to enqueue the
download request and the process starts.
d) Notice this line:
It simply places the file "sample.pdf" in your "/sdcard/Android/data/Your_Projec
ts_PackageName/files/" directory.This directory is private to your app only. It
will create this directory if doesn't exist already.
e) If You want the downloaded file to go to the default "Downloads" directory of
SD card, replace the above line with below line:
It's a public directory.
6. Now, Lastly, define the below two permissions in your AndroidManifest.xml fil
e:
7. Now, Either create Emulator with SD card or test it on device. After giving p
roper download URL and Clicking on "Download File" button, downloading will star
t and you can see the progress in Notification bar like screenshot below.
Retrieving Files from SD card:
1. There are several ways to retrieve the list of files present in a particular
directory of SD card. We'll be using the simplest approach.
2. Place the below code in your MainActivity.java file's OnCreate method of main
activity:
3. The Above code simply generates the list of files present in app's data folde
r and displays the list in Edit Text. (if there is no permission or access error
).
Studio
in Creating a New Project, either choose Start a
the Android Studio homepage, or from the Android
New > New Project. Fill out the fields in the re
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="@color/colorPrimary"
android:text="@string/hello" />
</RelativeLayout>
The Manifest File
Next, we must modify the manifest file because we are going to need explicit per
mission to write to external files. Open AndroidManifest.xml and edit it to read
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="<YourNamespace>.writesdcard">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
where the added permission WRITE_EXTERNAL_STORAGE is highlighted in red.
Before Android 4.4 (API 19), reading files on the external file system required
theREAD_EXTERNAL_STORAGE permission, and writing to external storage required th
eWRITE_EXTERNAL_STORAGE. (If you needed to do both, the read permission is impli
cit in the write permission, so it was only necessary to acquire the write permi
ssion in that case.)
Beginning with Android 4.4, these permissions are not required if you are are re
ading or writing only files that are private to your app. This is why the androi
d:maxSdkVersion="18" attribute is included in the permission request in the mani
fest file. We shall explain this app-specific storage that does not require writ
e permission further below . You should be aware that there are some limitations
associated with this convenience. For example, if the user uninstalls your app,
all of these app-specific data directories are erased, and the system media sca
nner does not scan these directories, making them inaccessible to the MediaStore
content provider (see saving files that are app-private).
Hence you should not use these app-specific directories for media that belongs u
ltimately to the user. Examples: user photos captured or edited with your app, o
r music the user has purchased with your app. In that case, the files should be
saved in the shared public directories (see saving files that can be shared with
other apps for further information). This project will concentrate on how to sa
ve and read files in the data area specific to this app.
The Java Class Files
Next, open the file java/<YourNamespace>.writesdcard/MainActivity.java and edit
it to read
package <YourNamespace>.writesdcard;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import
import
import
import
import
import
import
import
java.io.BufferedReader;
java.io.File;
java.io.FileNotFoundException;
java.io.FileOutputStream;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.io.PrintWriter;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MEDIA";
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
/**
* Method to check whether external media available and writable. This is ad
apted from
* http://developer.android.com/guide/topics/data/data-storage.html#filesExt
ernal
*/
private void checkExternalMedia() {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nEXTERNAL MEDIA: readable="
+ mExternalStorageAvailable + " writable=" + mExternalStorageWri
teable);
}
/**
* Method to write ascii text characters to file on SD card. In earlier vers
ions of Android a
* WRITE_EXTERNAL_STORAGE permission must be added to the manifest file or t
his method will throw
* a FileNotFound Exception because you won't have write permission. But not
true after
* API 18 for files in storage area of app (then no write permission require
d).
*/
private void writeToSDFile() {
// Root of the external file system
File root0 = android.os.Environment.getExternalStorageDirectory();
/* Now find the root of the external storage for this app (where the app
can place
* persistent files that it owns internal to the application and not typi
cally visible
* to the user as media). See
*
*
http://developer.android.com/guide/topics/data/data-storage.html#fi
lesExternal
*
* The method getExternalFilesDir (string) returns the user storage assoc
iated with the
* app, which doesn't require write permissions after API 18. The string
argument specifies various
* regions of this storage. For example,
*
* - null specifies the root of the storage for this app
* - Environment.DIRECTORY_NOTIFICATIONS specifies the Notifications dire
ctory of app storage
* - Environvment.DIRECTORY_DOWNLOADS specifies standard directory for fi
les downloaded by user
* - Environment.DIRECTORY_PICTURES specifies standard directory for pict
ures available to the user
* - Environment.DIRECTORY_DOCUMENTS specifies standard directory for doc
uments produced by user
* etc.
*
orage read/write permission is not required within the same package space but pa
ths belonging to other packages require read/write external media permissions (s
ee the documentation associated with getExternalFilesDir).
Setting Up the Path to the File
Now suppose that we wish create and write to a file called myData.txt in a subdi
rectory download of the root directory on the SD card for our app. The statement
s in MainActivity.java that set up the path up for that output are
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
The first line above creates a new instance of File using the constructor File(S
tring path), where path is the path to the "file" (which in this case is actuall
y going to be a directory).
To construct this path we first use the getAbsolutePath() method that root inher
its from File to return the absolute path corresponding to root (the root of the
external-storage file system for the app), and then we concatenate that with th
e string "/download". The net effect in this case will be to pass to the File co
nstructor the path
/storage/emulated/0/Android/data/com.lightcone.writesdcard/files/Documents/down
load
Then in the second line above we use the mkdirs() method of File, which creates
the corresponding directory.
Finally, in the third line above we define another instance of File called file
(in this case it actually is a file and not a directory), creating it using a di
fferent version of the constructor File(File directory, String filename), where
directory is the directory where the file is to be stored and filename is the na
me of the file.
Thus file now specifies the absolute path
/storage/emulated/0/Android/data/com.lightcone.writesdcard/files/Documents/down
load/myData.txt
to the file into which we wish to write.
In the discussion above two different forms of the constructor for File were use
d that have the same name but different argument lists:
1.
File(String path)
2.
File(File directory, String filename)
This is an example of what is called method overloading in object oriented progr
amming, where two or more definitions of a method exist having the same name but
different numbers and/or data types for method arguments.
The name and list of argument types for a method is called its signature. Thus t
he first method above has the signature File(String) while the second has the si
gnature File(File, String). Even though the overloaded methods share the same na
me, they have different signatures and the compiler can distinguish among them b
y examining their argument lists.
NOTE: Java does not consider the return type in distinguishing methods, so you c
annot define an overloaded method having the same signature but different return
types.
Writing Using Output Streams and Writers
To write to the file standard Java i/o stream capability is used, implemented in
terms of the classes
1.
FileOutputStream, which subclasses the abstract class OutputStream (the
superclass of all classes representing an output stream of bytes) and generates
a byte output stream.
2.
PrintWriter, which is used to wrap the FileOutputStream and provide frie
ndly user i/o (capability to deal with lines of ascii text rather than a byte st
ream).
The relevant code excerpted from the method writeToSDFile() is
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Howdy do to you.");
pw.println("Here is a second line.");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "File not found");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "I/O exception");
}
which creates a FileOutputStream, wraps it in a PrintWriter, and then appends li
nes to a file through this stream.
Handling Exceptions in the I/O
Note that all of the functional code above for the FileOuputStream is enclosed i
n a try-catch block. This is standard exception handling in Java.
1.
The constructor FileOutputStream(File file) for FileOutputStream throws
FileNotFoundException if theFile in its argument cannot be found.
2.
The method close() of FileOutputStream throws IOException if an error oc
curs in trying to close the stream.
Java requires that these exceptions be handled . The standard way to do that is
in a try-catch block, which has the general form
try {
// Code in which an exception might be thrown
.
.
} catch (ExceptionType name1) {
// Code to process exception type name1
.
.
} catch (ExceptionType name2) {
// Code to process exception type name2
.
.
}
where one or more appended catch blocks process the named exceptions thrown in t
he try block. For a more extensive discussion of try-catch blocks, start with th
e Java Tutorials. In the present code the two catchblocks deal respectively with
any FileNotFoundException or IOException that might be thrown in the tryblock.
For the catch block corresponding to FileNotFoundException we first invoke the p
rintStackTrace() method that FileNotFoundException inherits from Throwable, whic
h sends a human-readable form of theThrowable's stack trace to the System.err st
ream.
Throwable is the superclass of all Java errors and exceptions that can be thrown
by the virtual machine. It has two direct subclasses:
1.
Exception, which corresponds to recoverable errors, and
2.
Error, which corresponds to unrecoverable errors.
A file that is stored in the res/raw directory of the project will be exported w
ith the application when it is packaged in the APK file and thus can be accessed
from the application by this approach. (Theres/raw directory is not compressed
when it is stored in the application.) The methodopenRawResource(int resourceID)
can be used to open only drawable, sound, and raw resources; it will fail if yo
u try to open string or color resources with it. A file stored in the res/raw di
rectory is readable by the application at runtime, but not writable.
An InputStreamReader instance isr is then created using the constructor with the
InputStream is as argument. AnInputStreamReader reads a buffer of bytes from th
e source stream and converts these into characters as needed.
Finally, we create a BufferedReader from isr using the constructor BufferedReade
r(Reader reader, int buffsize), where reader is an instance of the class Reader
and buffsize is the size of the read-in buffer in bytes. (Reader is the supercla
ss of all readers, which are means of reading data character-wise from a source;
for example,InputStreamReader is a subclass of Reader.)
Our BufferedReader is an example of the buffered streams discussed above. Note t
hat in production code we would commonly replace
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192);
with the compound, chained expression
BufferedReader br = new BufferedReader(new InputStreamReader(
this.getResources().openRawResource(R.raw.textfile)), 8192);
since this is more compact and requires defining fewer variables. But it is also
less readable, and for our pedagogical purposes in the projects presented here
we often write expressions out as individual statements rather than compounding
them into more efficient expressions so that what is happening is clearer for th
e reader.
With our buffered input now set up we execute a while-loop, reading data in from
the file a line at a time using the readLine() method of BufferedReader.
Since readline() returns null when there are no more lines in the file, we check
for null and break from the while-loop when it is found. We then use the close(
) methods of the readers and streams to close them all.
Because readLine() and the close() methods throw the checked exception IOExcepti
on, we enclose all of this in atry-catch block to process any i/o exceptions.
Testing Read-In from a File
If you execute the application, you should find the lines that you put in the fi
le res/raw/textfile.txt displayed on the screen because of the tv.append() state
ment in the while-loop. As seen in the figure above, for my example I obtained
Now is the time
for all good men
to come to the aid
of their country.
which corresponds exactly to the four lines that I inserted in the file res/raw/
textfile.txt when it was created.
The complete project for the application described above is archived on GitHub a
t the linkWriteSDCard. Instructions for installing it in Android Studio may be f
ound in Packages for All Projects.
Last modified: July 8, 2016
Exercises
1. Use the methods of the File class to add a method to MainActivity that will l
ist the complete path to all files and directories on the SD card of the device,
and the size of the files in bytes. [Solution]