Use email address as file name in Android - java

Due to some requirement I want to save text files files to Android's file system and read it anytime programmatically.
For each user who will be using the same phone there will be a different text file stored. Unfortunately, at that time when the user has not logged in the only unique information about the user I have is the email address (or is there anything else?).
So my question is can I use the email address as the filename for these .txt files such as "xyz_123#email.com.txt" since the email address can have multiple special characters which I'm not sure are allowed in filenames?

Try this .
1.create
String email = "xyz_123#email.com";
File file = new File(email + ".txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("FILE_NAME", file.getName());
2.Add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
3.And you could use https://github.com/permissions-dispatcher/PermissionsDispatcher to request permission .

Related

How to move files from internal storage to app directory?

I am making a app that store files get files from Internal Storage and lock those files in app directory /data/data/[package_name]/videos/.
I try to move files files through this method but it is not working for me.
source.renameTo(new File("data/data/" + this.getPackageName() + "/files/videos/" + video_title));
TRIED BEFORE
I tried this
source.renameTo(new File("/storage/emulated/0/" + this.getPackageName() + video_title));. This worked and move file from soure to /storage/emulated/0/.
I also checked this directory exisits.
PROBLEM
Problem is file is not moving from storage to app directory.
This is the actual function I am using to move file.
private boolean moveFile(File source, File destination) {
boolean isDirectoryMade = false;
// creates directory if not exists
if (!destination.getParentFile().isDirectory()){
File parent = destination.getParentFile();
isDirectoryMade = parent.mkdirs();
}
// rename or move file.
boolean isFileRenamed = source.renameTo(destination);
return isDirectoryMade && isFileRenamed;
}
First, you'll have to copy that file to the app directory, reading the file using Storage Access Framework.
Then, still using SAF, you'll have to ask the user for delete the original one.
For both steps, Android now needs you to ask the user for accessing public directories, specifying if you read the file (the user will have to select the file manually) and delete it.
To ask the user for Document read, you'll have to use the following :
val selectFileRequest = registerForActivityResult(OpenDocument()) {
result: Uri? ->
//Your code to copy the file here, the provided Uri is the selected file's
//Then you can delete the file with the following:
if(result != null)
{
//DocumentFile.fromSingleUri(this, result)?.delete()
//or
//DocumentsContract.deleteDocument(getContentResolver(), result);
}
}
Don't forget to add the needed permissions in your Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
In the end, just call the following in your code:
selectFileRequest.launch(
arrayOf(
//Any Mime type you want to target, like the followings :
"application/pdf",
"image/*",
"text/*"
)
)

Google Drive revoke permissions on shared files

I want to revoke permissions on a shared file on my Google Drive Account.
String fileId = "abc1234";
String permissionId = "abc1234";
try
{
service.permissions().delete(fileId, permissionId).execute();
}//try
catch (IOException e)
{
System.out.println("An error occurred: " + e);
}//catch
I think the problem here might be the permissionId's value. Does anyone know how can get the right one? Also, is this the right way to revoke someone's permissions on a file?
I would recommend doing a Permissions: list
service.permissions().list(fileId).execute();
This will return a list of the permission on the file in question. Then you can find the permission that you want to delete and run your delete on that.

I can't write to /mnt/sdcard2 in Android

Now I'm making some version of File Manager in Andoid.
My permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
When I write new file to /mnt/sdcard (External Stroage) everything is allright.
But When i write new file to /mnt/sdcard2 (internal storage) I get IOException like
open failed: EACCES (Permission denied)
My full code:
try {
File existingFile = new File(path);
File newFile = new File(newPath);
if (!newFile.exists()) {
if (!isFolder)
{
newFile.createNewFile();
}
}
if (isFolder) {
FileUtils.copyDirectory(existingFile, newFile);
}
else
{
FileUtils.copyFile(existingFile, newFile);
}
} catch (IOException e) {
result = 1;
}
When i test my application I use real device.
My Path is like '/mnt/sdcard/Music/blabla' and so on
My Path is like '/mnt/sdcard/Music/blabla'
Do not use hardcoded paths as these may (and will) differ depending on device model or can even OS version. You got methods in Environment class to get you root folder of external storage and you should use it like getExternalStorageDirectory()
EDIT
. I need to get folder that contents folder like Music, DCIM, Download, but in Inner Storage of Smartphone
You cannot have "private" DCIM, Downloads really if you want to use system features like DownloadManager or external Camera app, because these apps will simply not be able to write to your private storage. So you either download/take photo yourself - then you can save the file whenever you want, or you use what is it now available, with all the pros and cons.
Name "external"/"internal" is a bit misleading nowadays, so do not take it too literally.

FileUtils.readFileToString IOException

I'm new to Android app development. Currently, I'm trying to get Android download folder path and log it. To do this, I use commons io library. I've got this code:
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.e("files", folder.listFiles().length + " items");
try {
String DFOLDER = FileUtils.readFileToString(folder);
Log.i(TAG2, DFOLDER);
}catch (IOException e){
Toast.makeText(getApplicationContext(), R.string.fail,
Toast.LENGTH_SHORT).show();
}
For some reason I'm getting IOException every time, but I'm receiving the amount of files in folder from 2nd line.
I've got this permissions in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
FileUtils.readFileToString Reads the contents of a file into a String. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) return a directory, not a file, so using readFileToString on it will throw an IOException. If you want to read the contents of all the files in the Download directory, do something like that.
File folder = Environment.getExternalStoragePublicDirectory(Environmeng t.DIRECTORY_DOWNLOADS);
for(File file:folder.listFiles()){
try {
String DFOLDER = FileUtils.readFileToString(file);
Log.i("File Contents ", DFOLDER);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
If there are too many files in that directory, it will probably throw an OutOfMemoryError.
EDIT: if you need the path of the foler use
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.i("Folder Path",folder.getAbsolutePath());
According to the Commons IO 2.4 API, the readFileToString method will take a file as parameter then read the contents of a file into a String. However,the getExternalStoragePublicDirectory method returns a folder instead of a file so calling readFileToString will throw an IO exception.

Private file for an app

I would like to create a file which stores some data that can be accessed only by my app.Outside users should not be able to access this file or make any changes to it.I will store a key in the file which maybe accessed by the app whenever needed.
Use Environment.getDataDirectory(),
http://developer.android.com/reference/android/os/Environment.html#getDataDirectory()
This gives a File object that is the path to a private, app specific data directory. The files created therein are owned by your app's user ID, preventing any other app from accessing them.
File myPrivateFile = new File(Environment.getDataDirectory(), context.getPackageName() + File.separator + "secret.txt");
Note that if the device is rooted, all bets are off. A root process can read any file on the device. The best you can do is only store information for user of the device. That way if it's compromised, only one user account is compromised. In other words, don't store credentials, keys, access tokens, etc. That would allow a malicious agent access to a server where it could steal data for other users.
To create an application private file (that is not readable by other applications) you should use Context.openFileOutput() with a flag MODE_PRIVATE.
If you are concerned you could wrap the returned InputStream in CiperOutputStream and encrypt the contents.
If you are storing keys in a standard crypto format (X.509 or PKCS#12) you could use the new KeyChain API introduced in ICS.
Why not just stored it in a SharedPreference ??
Make your SharedPreference private to your activity by calling..
getSharedPreferences(yourfile, MODE_PRIVATE);
This will make sure only your Activity can access that SharedPreference.
To open a file from a private app folder, one can use this file path:
File myFilePath = new File(getContext().getFilesDir() + File.separator + "myFile")
You can check if the file exists if(myFilePath.exists()) ...
To save a text file to the private app directory
FileOutputStream fos = null;
try {
fos = getContext().openFileOutput("myFile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) { }
try {
fos.write(myTextString.getBytes());
} catch (IOException e) { }
try {
fos.close();
} catch (IOException e) { }
To save an image to the private app directory:
try {
myBitmapImage.compress(CompressFormat.JPG, 90,
openFileOutput("myimage.jpg", MODE_PRIVATE));
} catch (Exception e) { }
Your best bet is to store an encrypted file and decrypt it run-time, so even a rooted phone would not be able to read your data even if it has access to it. Of course, it's a chicken-egg condition (where would you store your key for the encrypted file), and the only thing better than putting the key in a variable is to generate that key runtime using some obscure method (see this)

Categories

Resources