Save a file in Android - android

I'm currently using this code to store a file in Android:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/invoices";
File file = new File(dir, "Invoice.pdf");
This works perfectly fine in Genymotion emulator because ? but when I deploy the app to an Android phone, it doesn't work.
Can anyone explain why this maybe, or hint me to the right direction please, thanks in advance.

Add Permission in manifest file <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And Try This to Save File/Image

You should post all you did because from your code nobody can understand what you are exactly doing. However, take a look at the following links:
1. http://codetheory.in/android-saving-files-on-internal-and-external-storage/.
At the link mentioned above it explains you how to save in both internal and external SDcard.
2. http://developer.android.com/training/basics/data-storage/files.html.
Second link is from Google and it is a small brief about what you should do.
In all the cases don't forget about the permissions.
EDIT:
Below I attached a piece of code that it can help you:
public static File getNewFile(String fileName) throws IOException {
File file = null;
if (name == null) {
name = "temp_folder";
}
if (getInternalFilesDir() == null || !getInternalFilesDir().isDirectory()) {
file = null;
} else {
file = new File(getInternalFilesDir() + File.separator + TEMP_FOLDER + File.separator + fileName);
if (file.getParentFile() != null && ! file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file exists()) {
file.delete();
}
file.createNewFile();
if (! file.exists()) {
throw new IOException("Unable to create file " + name);
}
}
return file;
}
getInternalFilesDir is exactly that:
Save files in internal directory
//in the manifest now:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
other stuff
</manifest>

Related

Cannot create a file?

I have a problem with creating files in Android. I have followed this tutorial, and wrote this method:
public File getStorageDir(String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File file = new File(path, name);
System.out.println(path);
if (!file.mkdirs()) {
System.out.println("Directory not created");
}
return file;
}
Path variable prints /storage/emulated/0/Documents, however if goes off and no such directory is created. I have added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
permissions to manifest file. I have tried using file.getParentFile().mkdirs() but got same result. What am I doing wrong?
You use below code to create folder.
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "folderName");
if (!folder.exists()) {
success = folder.mkdirs();
}
So turns out it was being created the whole time, just not visible in file explorer. I have fixed it with answer from this post. Final code looks like this:
public File getStorageDir(Context context, String name) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getPath();
File file = new File(path, name);
file.getParentFile().mkdirs();
MediaScannerConnection.scanFile(context, new String[] {path}, null, null);
return file;
}
Thanks everyone for answers, hope this helps someone who faces same problem.

Android Studios Serialization. Attempt to get length of null array

Okay, so in my project I am trying to serialize a chess game by writing to a folder named data. I did this in eclipse, and it was able to work. However, when I brought it into android studios I got the error of trying to get the length of a null array. Here is my method:
public static void writeData() throws IOException {
System.out.println("WRiting data");
File folder = new File("data" + File.separator);
folder.mkdir();
String[] directories = folder.list();
for (String name : directories) { //error here
File ff = new File(folder + File.separator + name);
if (ff.isDirectory()) {
deleteDirectory(ff);
}
}
//add all user data
for (game u : info.games) {
File f = new File("data" + File.separator + u.name); //make a file with user name
f.mkdir(); //make the file a directory
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(f + File.separator + "game-state"));
//create stream with file name at the end
oos.writeObject(u);
//write objects
oos.close();
}
}
Also, I looked at previous questions and changed my manifest file to allow for the permissions of writing and reading data.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The app does not crash when I read data. However, it crashes when I try to write data. Going crazy over here. Thank you for your help.
This may be due to marshmellow permission request ,you have to call permission request at runtime .
go through link
https://developer.android.com/training/permissions/requesting.html

How to create a .txt file in a specific directory in Android?

I am trying to develop a program which creates a file in a specific directory (.txt file) and stores some data in it (Strings for example). I also want that the file can be accessed by the user (If I go to file explorer I can view the file I've created and maybe edit it with another program or something).
I've tried many things, but I cant manage this to work.
Here is the code I am using atm:
public void createFile(View view) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sonda Drive Test";
File mypath = new File(filepath);
if(!mypath.exists()) {
mypath.mkdir();
}
//now the mkdir returns true isntead of false
File myfile = new File(mypath, fileName);
try{
if(!myfile.exists()){
txtDebug.setText("Não existe ficheiro!");
myfile.createNewFile();
}
else{
txtDebug.setText("Já existe ficheiro!");
}
}catch (Exception e){
txtDebug.setText("Erro!");
}
}
I've also added the permissions bellow:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
The problem is that when I do
myfile.createNewFile();
The application stops and closes.. But if I comment that line, it also won't create any file...
What am I doing wrong?
EDIT: I Manage to make this work for API 22. How can i do it for API 25?
you are putting the mypath as the path but you define the mypath as file

android mkdirs not working

i need to save an image from camera on android.
i used the write external storage permission in manifest and i am using this code
File dir = new File(Environment.getExternalStorageDirectory(), "Test");
if (!dir.exists() || !dir.isDirectory())
dir.mkdirs();
String path = dir.getAbsolutePath();
Log.d(TAG, path); //log show the path
File file = new File(dir.getAbsolutePath() + "/Pic.jpg");
Log.d(TAG, file.getAbsolutePath()); //again path is shown here
outStream = new FileOutputStream(file);
outStream.write(bytes);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + bytes.length); //fail here
} catch (FileNotFoundException e) {
Log.d(TAG, "not done"); //error is here (this exception is thrown)
} catch (IOException e) {
Log.d(TAG, "not");
} finally { }
i also tried mkdir() instead of mkdirs() same result.
any idea what went wrong in the code?
thanks
For those not as experienced like me. I fought this issue, lost hair for some time. I am targeting api 21 (for compatibility sake) and it worked on lollipop but on marshmallow it would not create the directory. I did have the "uses" permission in the manifest but it still would not work. Apparently in Marshmallow when you install with Android studio it never asks you if you should give it permission it just quietly fails, like you denied it. You must go into Settings, apps, select your application and flip the permission switch on.
Some one like me who was trying in Android10. Please use below API in manifest:
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
Latest Update From Google:
After you update your app to target Android 11, the system ignores the requestLegacyExternalStorage flag.
Did you put
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in your AndroidManifest? If you are using android M you must request user permission to write on sd, look here an example
IDIOT ME! i have used the Manifest Permission but when installed the app on phone i didnt grant permission for storage!... i understand a negative on this question... but i hope if someone else face the same..check your phone permission. sorry all for inconvenience.
you have created directory, not file. Create new file with following code
File file = new File(dir.getAbsolutePath() + "/Pic.jpg");
file.createNewFile()
if you are testing on android M, you should probably check Settings > App > Permission to see if permission to access storage is granted. This saved me.
if you already allowed R/W permission(Runtime Permission too) and still doesn't work add this below mentioned line in your AndroidManifest.xml
<application
........
........
android:requestLegacyExternalStorage="true">
Note: this must required if you'r targeting Android 10+
Starting from API 30 you can only write in your app-specific files
File dir = new File(context.getFilesDir(), "YOUR_DIR");
dir.mkdirs();
or in the external storage of your app Android/data
File dir = new File(myContext.getExternalFilesDir("FolderName"),"YOUR_DIR");
UPDATE
this answer provided another solution https://stackoverflow.com/a/65744517/8195076
UPDATE
another way is to grant this permission in manifest
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
like this answer https://stackoverflow.com/a/66968986/8195076
Try this. Provide runtime permission for marshmallow it is perfectly work in my Application code :
private String getFilename(String strFileName) {
String filepath = Environment.getExternalStorageDirectory().getPath();
File fileBase = new File(filepath, "Test");
if (!fileBase.exists()) {
fileBase.mkdirs();
}
return (file.getAbsolutePath() + "/" + strFileName + file_exts[currentFormat]);
}
new File(getFilename(edt.getText().toString().trim()))
outputFile = new File(apkStorage + "/" + downloadFileName );
//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
isExternalStorageWritable();
outputFile.getParentFile().mkdirs();
outputFile.createNewFile();
Log.e(TAG, "File Created");
OutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream fis = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = fis.read(buffer)) >0) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
fis.close();
I wrote this code for creating a file, but it is not working in android 11
when writing code for android API 29 and above use the following permission in your application manifest (AndroidManifest.xml)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Adjust your code to read like the following
ActivityCompat.requestPermissions(this, new String[]
{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
},
PackageManager.PERMISSION_GRANTED);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
file = new File(Environment.getExternalStorageDirectory().getPath(), "TestDirectory/Document/");
if (!file.exists()) {
try {
file.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}

android - file.exists() returns false for existing file (for anything different than pdf)

Both files are present on the sdcard, but for whatever reason exists() returns false the the png file.
//String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png";
String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-1200240592.pdf";
File file2 = new File(path);
if (null != file2)
{
if(file2.exists())
{
LOG.x("file exist");
}
else
{
LOG.x("file does not exist");
}
}
Now, I've look at what's under the hood, what the method file.exists() does actually and this is what it does:
public boolean exists()
{
return doAccess(F_OK);
}
private boolean doAccess(int mode)
{
try
{
return Libcore.os.access(path, mode);
}
catch (ErrnoException errnoException)
{
return false;
}
}
May it be that the method finishes by throwing the exception and returning false?
If so,
how can I make this work
what other options to check if a file exists on the sdcard are available for use?
Thanks.
1 You need get the permission of device
Add this to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2 Get the external storage directory
File sdDir = Environment.getExternalStorageDirectory();
3 At last, check the file
File file = new File(sdDir + filename /* what you want to load in SD card */);
if (!file.canRead()) {
return false;
}
return true;
Note: filename is the path in the sdcard, not in root.
For example: you want find
/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
then filename is
./Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
.
Please try this code. Hope it should helpful for you. I am using this code only. Its working fine for me to find the file is exists or not. Please try and let me know.
File file = new File(path);
if (!file.isFile()) {
Log.e("uploadFile", "Source File not exist :" + filePath);
}else{
Log.e("uploadFile","file exist");
}
Check that USB Storage is not connected to the PC. Since Android device is connected to the PC as storage the files are not available for the application and you get FALSE to File.Exists().
Check file exist in internal storage
Example : /storage/emulated/0/FOLDER_NAME/FILE_NAME.EXTENTION
check permission (write storage)
and check file exist or not
public static boolean isFilePresent(String fileName) {
return getFilePath(fileName).isFile();
}
get File from the file name
public static File getFilePath(String fileName){
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "FOLDER_NAME");
File filePath = new File(folder + "/" + fileName);
return filePath;
}

Categories

Resources