I am trying to open a CSV file downloaded into internal storage for reading purpose alone. This is the code I have used:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.FileInputStream;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
try {
String FileName = "/storage/emulated/0/Download/MyDocument.csv";
FileInputStream fis = openFileInput(FileName);
fis.read();
fis.close();
Toast.makeText(getBaseContext(),"File Access Permitted",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(),"File Access Denied",Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
While the file is downloaded and I am able to open it in File Manager, the above code does not work. How do I achieve the required functionality?
As per this stackoverflow question's accepted answer, you could try this:
public String readFileFromDownloads(String fileName) {
File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if (!downloadsDir.exists()) return null;
File file = new File(downloadsDir, fileName);
if (!file.exists()) return null;
try {
StringBuilder fileContent = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
fileContent.append(line);
fileContent.append('\n');
}
br.close();
return fileContent.toString();
} catch (IOException ex) {
//Handle error
return null;
}
}
And then call readFileFromDownloads("MyDocument.csv"); from inside your onClick(); method.
Also, you might need to add android.permission.READ_EXTERNAL_STORAGE to your Manifest and handle Android 6.0 new permission system as per Android Docs.
Related
Here's a code of MainActivity.java to save a file named filename.txt in App's Internal Storage, which is working fine.
package com.bla.smthing;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
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();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am able to see the file by File Explorer of Android Studio. How can I save the file in a directory say files/Somefolder/otherfolderchild/filename.txt?
Currently, it is saving as files/filename.txt
Do I need to create additional parent file directories for that?
Try this it might help you. For the above marshmallow version please check the write permissions.
public void saveToExternalStorage() {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "fileName.txt");
if(file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
Log.e("saveToExternalStorage()", e.getMessage());
}
}
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 display the contents of a text file?
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 depending on just what it is you want to do.
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 path - Android
You should have READ_EXTERNAL_STORAGE permission for reading sdcard.
Add permission in manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link
Permissions overview
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}
package com.example.readfilefromexternalresource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml");
reader = new BufferedReader(new FileReader(textFile));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} 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();
}
}
}
}
}
}
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
Beware: some phones have 2 sdcards , an internal fixed one and a removable card.
You can find the name of the last one via a standard app:"Mijn Bestanden" ( in English: "MyFiles" ? )
When I open this app (item:all files) the path of the open folder is "/sdcard" ,scrolling down there is an entry "external-sd" , clicking this opens the folder "/sdcard/external_sd/" .
Suppose I want to open a text-file "MyBooks.txt" I would use something as :
String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ;
File file = new File(fname);...etc...
Here is my source code;
I've installed microsdsvc app on the external_SD.
szSDCardFileName = "/storage/external_SD/Android/data/com.tmnt.microsdsvc/files/AAA.DAT";
if ((fp = open(szSDCardFileName, O_RDWR|O_DIRECT|O_SYNC, S_IRWXU)) == -1) {
if ((fp = open(szSDCardFileName, O_RDWR|O_DIRECT|O_SYNC|O_CREAT, S_IRWXU)) == -1) {
return -1;
}
}
memset(g_buf, 0x00, BLOCK_LENGTH);
if (read(fp, (char *)g_buf, BLOCK_LENGTH) == ERROR) {
__android_log_print(ANDROID_LOG_INFO, "JNI", "<Err>file read error[errno=%d, handle=%d]", errno, fp);
return -1;
}
when running the code on the Lg G2 Kitkat version, open() is OK, but next read() is failed with errorno 22.
I don't know that what I mistake!!
Maybe this is the reason why...
KitKat, applications will no longer be able to create, modify, or remove files and folders on 'secondary external storage device' respectively dual-storage devices with internal flash AND a removable / external SD card.
"The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external storage on a device. Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."
http://source.android.com/devices/tech/storage/index.html
package com.example.readfilefromexternalresource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
File file = Environment.getExternalStorageDirectory();
File file2 = new File(file.getAbsolutePath()+File.separator + "myText.txt");
reader = new BufferedReader(new FileReader(file2));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} 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();
}
}
}
}
}
}
First you need to get the state of your external sd card
then you check if there is a mounted sd card, if no sd card its found, it will do nothing(you can put error msgs here)
get its absolute path and add a separator then put the file name of the file you want to read
use a BufferedReader to read your textFile.
Use a StringBuilder to build your string, it is more efficient than simple concatinating strings
after appending your strings, always close the reader to save memory, smartphones are known to have less memory than desktop
call to toString() method of the StringBuiler to create your String which you can use
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)) {
} else {
File externalDir = Environment.getExternalStorageDirectory();
File textFile = new File(externalDir.getAbsolutePath()
+ File.separator + fileName);
BufferedReader reader
= new BufferedReader(new FileReader(textFile));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
reader.close();
String yourString = textBuilder.toString();
}
it throws a FileNotFound exception btw. You can do the same in writing a file.
The file model.obj is in the assets directory of my project. The toast that comes out is a File Not Found exception. I am running the program on my Galaxy S3 not a virtual device. Do I have to specify some path to the file?
Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import android.content.Context;
import android.app.Activity;
public class ImportOBJ {
protected void onCreate(String filename,Context context)
{
try
{
FileInputStream fis = context.openFileInput(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while( (line = reader.readLine()) != null )
{
input += line;
}
reader.close();
fis.close();
}
catch (Exception ex)
{
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
ManActivity:
package com.example.tictactoeshowgrid;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImportOBJ obj_import=new ImportOBJ();
obj_import.onCreate("model.obj",MainActivity.this);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Use the following code to get the file from asset manager:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("foo.txt");
if ( inputStream != null)
Log.d(TAG, "It worked!");
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fis = context.openFileInput(filename);
Can be replaced with
InputStream fis = context.getAssets().open(filename);
GetAssets() returns an AssetManager:
Provides access to an application's raw asset files; see Resources for the way most applications will want to retrieve their resource data. This class presents a lower-level API that allows you to open and read raw files that have been bundled with the application as a simple stream of bytes.
the path is assets/file/model.obj, you can read file like this
InputStream fis = mContext.getAssets().open("file/model.obj");
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 display the contents of a text file?
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 depending on just what it is you want to do.
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 path - Android
You should have READ_EXTERNAL_STORAGE permission for reading sdcard.
Add permission in manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link
Permissions overview
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}
package com.example.readfilefromexternalresource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml");
reader = new BufferedReader(new FileReader(textFile));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} 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();
}
}
}
}
}
}
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
Beware: some phones have 2 sdcards , an internal fixed one and a removable card.
You can find the name of the last one via a standard app:"Mijn Bestanden" ( in English: "MyFiles" ? )
When I open this app (item:all files) the path of the open folder is "/sdcard" ,scrolling down there is an entry "external-sd" , clicking this opens the folder "/sdcard/external_sd/" .
Suppose I want to open a text-file "MyBooks.txt" I would use something as :
String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ;
File file = new File(fname);...etc...