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*/
Related
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.
I must transfer a data file necessary for my app.
I read many threads on the subject and I stll don't understand how it works.
1. I'm using android studio 0.8.6. A lot of threads mentions the folder assets which apparently resides in src/main. When I create a new project the folder doesn't exist. I create manually one and I put in it jpg and txt files.
2. I run the following code:
AssetManager am = getAssets();
String[] files = new String[0];
try {
files = am.list("Files ;
} catch (IOException e) {
e.printStackTrace();
}
for(int i=0;i<files.length;i++){
Toast.makeText(getApplicationContext(), "File: "+files[i]+" ", Toast.LENGTH_SHORT).show();
}
And I get a files.length = 0
1. I can create files, write in it and read it but I don know where they reside.
And that's not what I want to do. I want to pass the data with the app.
Sorry for the long email but I'm lost.
Thanks in advance!
The code I have used to read files from assets is listed below:
public String ReadFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
This code is not mine and can be found in the answers below:
read file from assets
I did some progress using the following code:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
File dir = getFilesDir();
File f = new File("/data/data/com.example.bernard.myapp/");
File file[] = f.listFiles();
for(int i=0;i<file.length;i++){
Toast.makeText(getApplicationContext(), "File: "+String.valueOf(file[i]), Toast.LENGTH_SHORT).show();
}
}
I code in hard what seems to me like the root of my app:
File f = new File("/data/data/com.example.bernard.myapp/");
The result is I can see 3 files: lib, cache, files
in "files" appears the files I create running the app.
I still don't know where is assets, neither where I transfer/put the .txt and .jpg files I want to use with my app. I develop using studio.
I am developing an android app which needs to copy the existing XML file from assets folder to external storagewhile installing the apk file in device . Is there any inbuilt function for it or other technique to call my method while installing apk file.
Thanks in Advance.
You can copy your xml file from assets folder by given code :
File toPath = Environment.getExternalStoragePublicDirectory(mAppDirectory);
if (!toPath.exists()) {
toPath.mkdir();
}
try {
InputStream inStream = getAssets().open("file.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
File toFile = new File(toPath, "file.xml");
copyAssetFile(br, toFile);
} catch (IOException e) {
}
private void copyAssetFile(BufferedReader br, File toFile) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(toFile));
int in;
while ((in = br.read()) != -1) {
bw.write(in);
}
} finally {
if (bw != null) {
bw.close();
}
br.close();
}
}
Reference : LINK
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*/
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");
}