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.
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.
Reading a large text file with over 130000 line of text
Since you are processing a large file, you should process the data in chunks . Here your file reading is fine but then you keep adding all rows in string buffer and finally passing to Toast.makeText(). It creates a big foot-print in memory. Instead you can read 100-100 lines and call Toast.makeText() to process in chunks. One more thing, use string builder instead of string buffer go avoid unwanted overhead of synchronization. You initializing wwwdf2 variable inside the method but looks it is a instance variable which I think is not required. Declare it inside method to make it's scope shorter.
Related Topics
Why Does My Function That Calls an API or Launches a Coroutine Return an Empty or Null Value
Inner Class Can Access But Not Update Values - Asynctask
Android - Start Service on Boot
Java Processbuilder: Resultant Process Hangs
What Is Pecs (Producer Extends Consumer Super)
Connect to Kafka Running in Docker
What's Wrong With Overridable Method Calls in Constructors
Unsupported Major.Minor Version 52.0
How to Set Java_Home on Windows 7
How to Return a Documentsnapshot as a Result of a Method
Launching Google Maps Directions Via an Intent on Android
Why Retrieving Google Directions For Android Using Kml Data Is Not Working Anymore
Java Can't Connect to X11 Window Server Using 'Localhost:10.0' as the Value of the Display Variable
How to Upload Files to a Server Using Jsp/Servlet