read from text file in android - android

I am new in android development, and I'm trying to create a simple application which reads some data from a text file and displays it in a ListView. The problem is my reader doesn't find my file. I've debugged my application and that is the conclusion I've come up with. So, where does the text file have to placed in order for the reader to find it?
Heres some code:
try
{
FileInputStream fstream = new FileInputStream("movies.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
filme.add(strLine);
Log.d(LOG_TAG,"movie name:" + strLine);
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
Thanks!

Put the file named movies.txt in res/raw, then use the following code
String displayText = "";
try {
InputStream fileStream = getResources().openRawResource(
R.raw.movies);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
} catch (IOException e) {
// exception handling
}

FileInputStream fstream = new FileInputStream("movies.txt");
where is the path for movies.txt ?? You must need to give the path as sd card or internal storage wherever you have stored.
As if, it is in sd card
FileInputStream fstream = new FileInputStream("/sdcard/movies.txt");

Usually when you want to open a file you put it into the res folder of your project.
When you want to open a text file, you can put it into the res/raw directory. Your Android eclipse plugin will generate a Resource class for you containing a handle to your textfile.
To access your file you can use this in your activity:
InputStream ins = getResources().openRawResource(R.raw.movies);
where "movies" is the name of your file without the filetype.

If you store your files on the SD card, then you can get the root of the SD card with Environment.getExternalStorageDirectory().
Note, that you might not be able to access the SD card, if it is mounted to the computer for example.
You can check the state of the external storage like this:
boolean externalStorageAvailable = false;
boolean externalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
externalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
externalStorageAvailable = true;
externalStorageWriteable = false;
} else {
externalStorageAvailable = mExternalStorageWriteable = false;
}
if(externalStorageAvailable && externalStorageWriteable){
File sdRoot = Environment.getExternalStorageDirectory();
File myFile = new File(sdRoot, "path/to/my/file.txt");
}

Related

write text file in res/raw folder

I have a text file in folder res/raw name "pass.txt" and some data in it i want to delete this data and enter new data in it.... is it possible to write data on it?? otherwise what is correct path to store my text file so i can easily read/write data on it.... and what is the code to read and write data from it?? below is the code through which i can only read data from this text file
InputStream fr = getResources().openRawResource(R.raw.pass);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
String s=br.readLine().toString().trim();
Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime.
Look at Internal or External Data Storage APIs to read write files.
https://developer.android.com/training/basics/data-storage/files.html
you can use Android internal storage to Read and write file ... as res/raw is only Read only..you can not change content at runtime.
Here is the code:
Create file
String MY_FILE_NAME = “mytextfile.txt”;
// Create a new output file stream
FileOutputStream fileos = openFileOutput(MY_FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fileis = openFileInput(My_FILE_NAME);
Read from file:
public void Read(){
static final int READ_BLOCK_SIZE = 100;
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Write to file:
public void Write(){
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("TEST STRING..");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}

Opening a textfle and pushing it to parse cloud (android)

I have a textfile in /sdcard/applit/mytext.txt
I want to push it to parse cloud.Googled a lot but No profit.Please explain completely.Thanx.
private void txtPusher(File dir) throws IOException {
File outputFile;
outputFile=newFile(dir,"MyText\t"+ParseUser.getCurrentUser().getUsername()+".txt");
byte [] b;
b=FileUtils.readFileToByteArray(outputFile);
file=new ParseFile("MyText\t"+ParseUser.getCurrentUser().getUsername()+".txt",b);
file.saveInBackground();
TextPusher Tpusher=new TextPusher(file);
Tpusher.execute();
}
Here dir is the directory I am passing to txtPusher function.I want to know wether output file is that file which I am going to push or another directory or it is creating a new file.but my file is not getting pushed.If i am wrong please share the right way to push the textfile
You can read the contents of a text (.txt) file using the following:
private String readFile(String fileName) {
//Find the directory for the SD Card using the API
File sdcard = new File(Environment.getExternalStorageDirectory() + File.separator + "Inventory_Files/Version/");
// Get the text file
File file = new File(sdcard, fileName);
// 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
}
return text.toString();
}
As for sending this data to the cloud, this looks to be very well documented on their site.

Is it possible that a .apk file be run without Wifi?

I just used this to create a .apk file of my website. Is it possible that this file be run without accessing data connections or wifi? But all the same, the website should get updated when the Wifi or data is switched on. Anyone have anything that can help me?
First store your website's file in asset folder.
Now everytime you open the app, check if the website file exists or not to prevent app from crashing.
The code given below checks that and if it doesn't exist, then it calls a method which copies the file from asset to device storage.
File file = new File(YOUR FILE PATH);
if(!file.exists()){
//Doesn't exist. Create it in sdcard
copyAssets();
}
Here are the methods to copy the website file from asset to device storage (put them in your class) -
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(DIRECTORY, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Then check internet connection of user (in oncreate method) -
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//user is connected to internet
//put the code given ahead over here
}
Permission -
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now if the user is connected to the internet, access the internet and get your website's new source code like this (put this code in internet checking code given above) -
URL url = new URL(YOUR URL);
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
String source = a.toString();
Now once you have the source code, update your HTML file in device storage like this -
File gpxfile = new File(File address, "filename.html");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write(source); //our new source code
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
You are done! Now load your file to webView from storage like this (in oncreate method after all the code that we wrote before) -
index.loadUrl("file://"+Environment.getExternalStorageDirectory()+ "Your address in storage");
It is recommended to send user requests time to time to turn on their internet to update the website and prevent use of outdated copy of it.

how do you read a file(media) on a users sdcard and display the media on your app (android) [duplicate]

how to read a specific file from sdcard. i have pushed the file in sdcard through DDMS and i am trying to read it though this way but this give me exception. can anybody tell me how to point exactly on that file?
my code is this.
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream = new FileInputStream(path);
You are trying to read a directory... what you need is the file! Do something like this... then, you can read the file as you want.
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
To read any file(CSV in my case) from External Storage, we need a path for it,once you have path you can do like this...
void readFileData(String path) throws FileNotFoundException
{
String[] data;
File file = new File(path);
if (file.exists())
{
BufferedReader br = new BufferedReader(new FileReader(file));
try
{
String csvLine;
while ((csvLine = br.readLine()) != null)
{
data=csvLine.split(",");
try
{
Toast.makeText(getApplicationContext(),data[0]+" "+data[1],Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Log.e("Problem",e.toString());
}
}
}
catch (IOException ex)
{
throw new RuntimeException("Error in reading CSV file: "+ex);
}
}
else
{
Toast.makeText(getApplicationContext(),"file not exists",Toast.LENGTH_SHORT).show();
}
}
/*
csv file data
17IT1,GOOGLE
17IT2,AMAZON
17IT3,FACEBOOK*/

Android application how to store and get a file inside the application

I have an application that make me choose a file through a file explorer(the file is stored on the sd), and then reads it.
I want to modify it, so it has the file directly into the app and reads the file from "inside". Where I have to put the file into the project? How can I access it?
You can save a file inside your project by using the following code:
File cDir = getApplication().getExternalFilesDir(null);
File saveFilePath = new File(cDir.getPath() + "/" + "yourfilename");
You can see the saved file inside "files" folder of your application package name in your device.
Try the following path in your device:
File manager >> Android >> data >> "your package name" >> files >> new file.
Yes, you can put your file into /assets folder, and retrieve as follows:
AssetManager assetManager = getAssets();
InputStream instream = assetManager.open("file.txt");
or res/raw folder:
InputStream raw = getResources().openRawResource(R.raw.file);
If you want to modify it, you'll be able only to write a file into External storage (e.g. sdcard),
or into Internal storage (under your application folder data/data/package_name/).
If you store your file into External storage it will persist until user manually or programmatically deletes the file. But if you store this file into Internal storage, it will be deleted if user deletes an app, or clear an application cache.
Demo
File myExternalFile;
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveToExternalStorage.setEnabled(false);
} else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
save External Storage (FileOutputStream )
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(myInputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText("");
responseText.setText("Saved to External Storage.(StorageFile.txt)");
Get External Storage (FileInputStream )
try {
FileInputStream fis = new FileInputStream(myExternalFile);
BufferedReader br = new BufferedReader(
new InputStreamReader(fis));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);
responseText
.setText("Data retrieved from Internal Storage.(StorageFile.txt)");

Categories

Resources