I am using this code to save some text in the external storage.
String fileName = "zadTest";
String text = "Hello World!";
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File textFile = new File(Environment.getExternalStorageDirectory(),fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(textFile);
fos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But I don't know where to look for it exactly so I can't check if I am doing this correctly and I don't know if I really put some data into external storage. I checked my SD card but couldn't find it I also tried to run this app on emulator but also cant find the file.
I have put these in the manifest:
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
Additional question: Should I bother with "finally" in try/catch blocks or should I just put all the code in "try" and skip "finally"?
Here I placed code with run-time permission put this and check again
Put this permission in on create and call request permission in that.
private static final int REQUEST_CODE = 101;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermission(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
} else {
String fileName = "zadTest";
String text = "Hello World!";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File textFile = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(textFile);
fos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
After permission code, call this method
protected void requestPermission(String[] permissionType, int
requestCode) {
ActivityCompat.requestPermissions(this,
permissionType, requestCode
);
}
I have enabled the user to select a specific file from his device the extension of the file is .txt , and I'm using MaterialFilePicker library for it , now how to convert this file to string base64 so I can send the file to the server.
if there's another library or another way to do it please recommend me to use it.
this the code I tried but it didn't work out , thanks.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSIONS_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openFilePicker();
} else {
showError();
}
}
}
}
// FILE PICKER
private void checkPermissionsAndOpenFilePicker() {
String permission = Manifest.permission.READ_EXTERNAL_STORAGE;
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
showError();
} else {
ActivityCompat.requestPermissions(this, new String[]{permission}, PERMISSIONS_REQUEST_CODE);
}
} else {
openFilePicker();
}
}
private void showError() {
Toast.makeText(this, "Allow external storage reading", Toast.LENGTH_SHORT).show();
}
private void openFilePicker() {
new MaterialFilePicker()
.withActivity(this)
.withRequestCode(FILE_PICKER_REQUEST_CODE)
.withHiddenFiles(true)
.withTitle("Sample title")
.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
String path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
if (path != null) {
Log.d("Path: ", path);
file = new File(path);
fileStr = String.valueOf(file);
Toast.makeText(this, "Picked file: " + file, Toast.LENGTH_LONG).show();
}
}
}
//convert the file path to base64
public static String encodeImage(String path) {
File imagefile = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
if (fis != null) {
try {
fis.close();
if (baos != null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Base64.de
return encImage;
}
First read the file to a byte array, and then use
Base64.encodeToString(byte[], int)
to convert it to a Base64 string.
Try this:
File file = new File("myfile.txt");
//convert file to byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(file);
bos.close();
oos.close();
byte[] bytearray = bos.toByteArray();
//convert byte[] to file
ByteArrayInputStream bis = new ByteArrayInputStream(bytearray);
ObjectInputStream ois = new ObjectInputStream(bis);
File fileFromBytes = null;
fileFromBytes = (File) ois.readObject();
bis.close();
ois.close();
System.out.println(fileFromBytes);
Note: Don't forget to handle the exception(try/catch)
I am trying to read a file from external SD card in android Marshmallow 6.0.1 and want to convert in byte, but it is giving fileNotFoundException. But my same code is working for 6.0 and below. My code is as follows:
private String convertFileToByteArray(File file) { //file path as: /storage/emulated/0/abc.doc
byte[] byteArray = null;
try {
File f=new File(file.toString());
Log.e("File EXISTs: >>",""+f.exists());
//getting error in this line,giving fileNotFoundException
FileInputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 11];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
Log.e("Byte array", ">" + byteArray);
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(byteArray, Base64.NO_WRAP);
}
Can any one suggest me what's wrong i am doing here.
PS: I am giving runtime permissions also.
In marshmallow use this code for external storage in try block.
public boolean isexternalStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (android.Manifest.permission.WRITE_EXTERNAL_STORAGE == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
use permission
Please go through the documentation
I want to make local copy(external storage) of a '.ppt' file present on Google Drive using Google Drive android Api.
I am reading one byte and writing it to my local file. But when I am trying to open it shows that file is corrupt. Please help me to resolve my problem.
final DriveFile file = Drive.DriveApi.getFile(getClient(), fileid);
final Metadata[] metadata = new Metadata[1];
file.getMetadata(getClient())
.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
metadata[0] = metadataResult.getMetadata();
L.b(EditorWindow.this, metadata[0].getMimeType(), 0);
}
});
file.open(getClient(), DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
L.c("Error in creating new file");
return;
}
DriveContents contents = result.getDriveContents();
String filename = metadata[0].getTitle();
File localFile = new File(Environment.getExternalStorageDirectory(), filename);
OutputStream out = null;
InputStream in = null;
try {
out = new BufferedOutputStream(new FileOutputStream(localFile));
in = contents.getInputStream();
int b;
while ( (b = in.read()) > 0) {
out.write(b);
}
in.close();
out.close();
} catch (Exception e) {L.c("Error in writing to SD card");}
contents.discard(getClient());
}
});
Can you try changing your while condition to ( (b = in.read()) >= 0)? Note that 0 is a valid byte to be read from an InputStream.
http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()
I want to create a file in external storage sdCard and write to it.I have searched through internet and try but not getting the result,I have added permission in Android Manifest file as well,I am doing this on Emulator,I am trying the following code and getting a ERRR", "Could not create file".
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
//private Throwable e;
#Override
public void onClick(View v) {
// write on SD card file data from the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
} catch (Exception e) {
Log.e("ERRR", "Could not create file",e);
}
}// onClick
}); // btnWriteSDFile
You can do this with this code also.
public class WriteSDCard extends Activity {
private static final String TAG = "MEDIA";
private TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
checkExternalMedia();
writeToSDFile();
readRaw();
}
/** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
/** Method to read in a text file placed in the res/raw directory of the application. The
method reads in all lines of the file sequentially. */
private void readRaw(){
tv.append("\nData read from res/raw/textfile.txt:");
InputStream is = this.getResources().openRawResource(R.raw.textfile);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer size
// More efficient (less readable) implementation of above is the composite expression
/*BufferedReader br = new BufferedReader(new InputStreamReader(
this.getResources().openRawResource(R.raw.textfile)), 8192);*/
try {
String test;
while (true){
test = br.readLine();
// readLine() returns null if no more lines in the file
if(test == null) break;
tv.append("\n"+" "+test);
}
isr.close();
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nThat is all");
}
}
To write into external storage in Lollipop+ devices we need:
Add the following permission into Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Request an approval from the user:
public static final int REQUEST_WRITE_STORAGE = 112;
private requestPermission(Activity context) {
boolean hasPermission = (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
} else {
// You are allowed to write external storage:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/new_folder";
File storageDir = new File(path);
if (!storageDir.exists() && !storageDir.mkdirs()) {
// This should never happen - log handled exception!
}
}
Handle the user response inside Activity:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case Preferences.REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "The app was allowed to write to your storage!", Toast.LENGTH_LONG).show();
// Reload the activity with permission granted or use the features what required the permission
} else {
Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
Even though above answers are correct, I wanna add a notice to distinguish types of storage:
Internal storage: It should say 'private storage' because it belongs to the app and cannot be shared. Where it's saved is based on where the app installed. If the app was installed on an SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...), your file will belong to the app means your file will be in an SD card. And if the app was installed on an Internal card (I mean the onboard storage card coming with your cell phone), your file will be in an Internal card.
External storage: It should say 'public storage' because it can be shared. And this mode divides into 2 groups: private external storage and public external storage. Basically, they are nearly the same, you can consult more from this site: https://developer.android.com/training/data-storage/files
A real SD card (I mean the external storage card you put more into a cell phone for more space to store images, videos, ...): this was not stated clearly on Android docs, so many people might be confused with how to save files in this card.
Here is the link to source code for cases I mentioned above: https://github.com/mttdat/utils/blob/master/utils/src/main/java/mttdat/utils/FileUtils.java
The code below creates a Documents directory and then a sub-directory for the application and saved the files to it.
public class loadDataTooDisk extends AsyncTask<String, Integer, String> {
String sdCardFileTxt;
#Override
protected String doInBackground(String... params)
{
//check to see if external storage is avalibel
checkState();
if(canW == canR == true)
{
//get the path to sdcard
File pathToExternalStorage = Environment.getExternalStorageDirectory();
//to this path add a new directory path and create new App dir (InstroList) in /documents Dir
File appDirectory = new File(pathToExternalStorage.getAbsolutePath() + "/documents/InstroList");
// have the object build the directory structure, if needed.
appDirectory.mkdirs();
//test to see if it is a Text file
if ( myNewFileName.endsWith(".txt") )
{
//Create a File for the output file data
File saveFilePath = new File (appDirectory, myNewFileName);
//Adds the textbox data to the file
try{
String newline = "\r\n";
FileOutputStream fos = new FileOutputStream (saveFilePath);
OutputStreamWriter OutDataWriter = new OutputStreamWriter(fos);
OutDataWriter.write(equipNo.getText() + newline);
// OutDataWriter.append(equipNo.getText() + newline);
OutDataWriter.append(equip_Type.getText() + newline);
OutDataWriter.append(equip_Make.getText()+ newline);
OutDataWriter.append(equipModel_No.getText()+ newline);
OutDataWriter.append(equip_Password.getText()+ newline);
OutDataWriter.append(equipWeb_Site.getText()+ newline);
//OutDataWriter.append(equipNotes.getText());
OutDataWriter.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
This one builds the file name
private String BuildNewFileName()
{ // creates a new filr name
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
StringBuilder sb = new StringBuilder();
sb.append(today.year + ""); // Year)
sb.append("_");
sb.append(today.monthDay + ""); // Day of the month (1-31)
sb.append("_");
sb.append(today.month + ""); // Month (0-11))
sb.append("_");
sb.append(today.format("%k:%M:%S")); // Current time
sb.append(".txt"); //Completed file name
myNewFileName = sb.toString();
//Replace (:) with (_)
myNewFileName = myNewFileName.replaceAll(":", "_");
return myNewFileName;
}
Hope this helps! It took me a long time to get it working.
You should read the documentation on storing stuff externally on Android. There's a multitude of problems that could exist with your current code, and I think going over the documentation might help you iron them out.
Supplemental Answer
After writing to external storage, some file managers don't see the file right away. This can be confusing if a user thinks they copied something to the SD card, but then can't find it there. So after you copy the file, run the following code to notify file managers of its presence.
MediaScannerConnection.scanFile(
context,
new String[]{myFile.getAbsolutePath()},
null,
null);
See the documentation and this answer for more.
You can find these method usefull in reading and writing data in android.
public void saveData(View view) {
String text = "This is the text in the file, this is the part of the issue of the name and also called the name od the college ";
FileOutputStream fos = null;
try {
fos = openFileOutput("FILE_NAME", MODE_PRIVATE);
fos.write(text.getBytes());
Toast.makeText(this, "Data is saved "+ getFilesDir(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos!= null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void logData(View view) {
FileInputStream fis = null;
try {
fis = openFileInput("FILE_NAME");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb= new StringBuilder();
String text;
while((text = br.readLine()) != null){
sb.append(text).append("\n");
Log.e("TAG", text
);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); //getappcontext for just this activity context get
File file = contextWrapper.getDir(file_path, Context.MODE_PRIVATE);
if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
{
saveToExternalStorage.setEnabled(false);
}
else
{
External_File = new File(getExternalFilesDir(file_path), file_name);//if ready then create a file for external
}
}
try
{
FileInputStream fis = new FileInputStream(External_File);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
myData = myData + strLine;
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
InputText.setText("Save data of External file:::: "+myData);
private static boolean isExternalStorageReadOnly()
{
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState))
{
return true;
}
return false;
}
private static boolean isExternalStorageAvailable()
{
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState))
{
return true;
}
return false;
}