How can I read a text file in Android?
Try this :
I assume your text file is on 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');
}
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.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
How to read text file in Android?
Android read text raw resource file
How read text file in Android?
You can use this code to get the files content instead of getting the path and read it again:
Uri uri = data.getData();
InputStreamReader inputStreamReader = new InputStreamReader(getContentResolver().openInputStream(uri));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String s;
while ((s = bufferedReader.readLine()) != null) {
sb.append(s);
}
String fileContent = sb.toString();
Note that these lines need to be wrapped into a try-catch block and don't forget to close the streams.
Android - How can I read a text file from a url?
Try using an HTTPUrlConnection or a OKHTTP Request to get the info, here try this:
Always do any kind of networking in a background thread else android will throw a NetworkOnMainThread Exception
new Thread(new Runnable(){
public void run(){
ArrayList<String> urls=new ArrayList<String>(); //to read each line
//TextView t; //to show the result, please declare and find it inside onCreate()
try {
// Create a URL for the desired page
URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location
//First open the connection
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000); // timing out in a minute
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (Exception e) {
Log.d("MyTag",e.toString());
}
//since we are in background thread, to post results we have to go back to ui thread. do the following for that
Activity.this.runOnUiThread(new Runnable(){
public void run(){
t.setText(urls.get(0)); // My TextFile has 3 lines
}
});
}
}).start();
Reading from a Text file in Android Studio Java
You should have a MainActivity.java
or some Activity
which instantiates QuoteBank
. You would want the constructor to take in a parameter of context:
Setup a private variable in QuoteBank.java
:
private Context mContext;
Setup up the constructor:
public QuoteBank(Context context) {
this.mContext = context;
}
Then instantiate it in your activity,
QuoteBank quoteBank = new QuoteBank(context);
The context variable can be called within an activity by the this
command or Activity.this
where you replace "Activity" with your activity name. Alternatively if you are within a fragment, you can get the context from the View
object inside your onCreateView(...)
method. Usually by calling view.getContext()
.
Now in your method where you are grabbing the assets, you can use the context:
InputStream is = mContext.getAssets().open("QuotesMonkeyBusiness.txt")
Since you're using android studio you can either create a main(String[] args) { ... }
method and run it or just start the emulator and have it use Log.d(...)
to show output from the file.
Alternatively you can use the following method as well:
AssetManager am = mContext.getAssets();
InputStream is = am.open("QuotesMonkeyBusiness.txt");
It might also make sense to have QuoteBank
as a singleton instance, that might increase efficiency although it all depends on your requirements, maybe something like:
List<String> allTextLines = QuoteBank.readFromFile(context, path_to_file);
And then in your QuoteBank.java
class you can have a method like so:
/**
* Created by AndyRoid on 5/23/15.
*/
public class QuoteBank {
private Context mContext;
public QuoteBank(Context context) {
this.mContext = context;
}
public List<String> readLine(String path) {
List<String> mLines = new ArrayList<>();
AssetManager am = mContext.getAssets();
try {
InputStream is = am.open(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null)
mLines.add(line);
} catch (IOException e) {
e.printStackTrace();
}
return mLines;
}
}
and then in my MainActivity.java
class I have the following:
/**
* Created by AndyRoid on 5/23/15.
*/
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String mPath = "adventur.txt";
private QuoteBank mQuoteBank;
private List<String> mLines;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQuoteBank = new QuoteBank(this);
mLines = mQuoteBank.readLine(mPath);
for (String string : mLines)
Log.d(TAG, string);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my project structure:
This is the adventur.txt
file I downloaded from a random database:
This is my log output:
UPDATE: Why you should not use a Scanner in Android
From the official documentation:
http://developer.android.com/reference/java/util/Scanner.html
This class is not as useful as it might seem. It's very inefficient for communicating between machines; you should use JSON, protobufs, or even XML for that. Very simple uses might get away with split(String). For input from humans, the use of locale-specific regular expressions make it not only expensive but also somewhat unpredictable.
The Scanner class is not thread-safe.
FINAL NOTE:
I highly suggest you read up on the documentation of all the objects used here so you can understand the process.
Related Topics
@Android Display /Res/Viewable in Webview
Getlaunchintentforpackage Is Null for Some Apps
The Import Android.Support.V7.App Cannot Be Resolved
Google Play Services Out of Date. Requires 11011000 But Found 10289574
Problem Loading Swf File in Android
How to Create a Dialogfragment Without Title
Android Navigation Drawer on Top Actionbar
Android - Wake Up and Unlock Device
Server-Side Verification of Google Play In-App Billing Version 3 Purchase
Garbage Collection Causes:Mediaplayer Finalized Without Being Released
Bufferoverflowexception When Building Application
How to Disable Proguard for Building My Android App
Getting Null Device Id While Registering to Gcm