Android File Permissions issues on FilesDir() - java

I need to use a file in my application. If i upload the file to Data/Data/APP/files then it is added with -rw-rw-rw permissions which i can then use in my application. If i programatically write the file to getFilesDir() the exact same directory, i can see the 2 exact files in the same directory, however the programatically saved file has permissions -rw------- i cannot then access the file in my app using getfilesDir().
this is how the file is saved:
public void writeFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
File file = new File(getApplicationContext().getFilesDir(), "");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
How can i get the correct permissions to use the file. It may well not be a permissions issue it maybe the way i am saving the file? It is a .graphml extension file.

What do you mean by cannot access your file?
Take a look at this documentation (https://developer.android.com/training/data-storage), you don't need permission to access (read and write) files inside App-Specific Directory.
Edit:
I'm assuming that you already stored the file to the disk.
Please note that to read and write files inside App-Specific Directory doesn't require permission. You can read it using this simple code.
public File readFile(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
// do other stuff, like checking if the file exist, etc.
return file;
}
It doesn't matter what file extension it is, as long as the file exists, you will get it.
Actually there are so many articles that already cover this topic, please take a look to understand this topic better.

Related

Google Drive API not downloading FIles (Java v3)

I'm using the code from here:
https://developers.google.com/drive/api/v3/manage-downloads#downloading_a_file
The code snippet I'm using is the following and placed in the main method:
String fileId = "some file ID";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
.executeMediaAndDownloadTo(outputStream);
I have found no sign of the code actually downloading the file, nor do I know where the file is IF it actually downloads.
I'm not sure if I am using the proper scope to gain permission to download files. I am able to upload, list, and delete files as long as I know the fileID, but downloading seems to not work.
private static final List<String> SCOPES = Collections.singletonList(DriveScopes.DRIVE);
Alternatively, I'm trying to create a method to enact the download protocol like so:
private static void downloadFile(Drive service, File file (or String fileID)){
}
but am not sure on how to do so. I've tried looking for samples online but most are from v1 or v2 apis and don't seem to work for me.
Also, I've read somewhere that it is not possible to download a Folder. Instead, I have to download each item in the folder one by one.
So do I have to make an Arraylist/list/array of the fileIDs and iterate through it after initializing a variable to represent fileID?
Edit: Some progress has been made, but I still have some problems I'm trying to thrash out.
List<File> files = result.getFiles();
File newFile;
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
String fileId = file.getId();
//System.out.println(fileId);
String fileName = file.getName();
//System.out.println(fileName);
OutputStream outputstream = new FileOutputStream();
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
outputstream.flush();
outputstream.close();
}
What I want:
The above code is in the main method. I don't know if this is the proper way to do it, but as the program fetches each file and executes the System.out.printf, I also want it to download that file (with the same mimeType, and pref the same name too) into the destination set in the OutputStream constructor (C://User//some name//Downloads).
What I've tried:
From what I've tested, it only downloads the first file exactly the way I want, but only because I specify the name and extension in OutputStream. I've initialized variables 'fileId' and 'fileName' so that they will change according to the info as the program fetches the metadata for the next file, but I don't know how to change or set multiple constructors into this code:
OutputStream outputstream = new FileOutputStream();
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
to download all the files.
My folder hierarchy in Google Drive is like this:
Logs
-- bin (folder)
---- bunch of .bin files
-- .xml file
-- .xml file
You are using a ByteArrayOutputStream object as the output of your download. If your program terminates without having saved the contents of this object somewhere, you will not be able to find this information in your computer's disk, as it is not written to it but rather saved in memory as a buffered byte-array (refer to the previous link for more information).
If you want to save the output of the download to the file, I suggest you use instead a FileOutputStream as the destination of your download. In order to do that, you have to modify your code as follows:
Add the appropriate import declaration:
import java.io.FileOutputStream;
Modify your outputStream variable assignment as follows:
OutputStream outputStream = new FileOutputStream('/tmp/downloadedfile');
Where the parameter passed to FileOutputStream should be the desired destination path of your download.
After writing any contents to your file, add the following lines of code:
outputStream.flush();
outputStream.close();
This will ensure that your file is being written to properly.
In regards to downloading a folder, you are completely right - you will first need to fetch the folder you want to download, and each of their children. In order to better understand how to do it, I suggest you check out the following answer: Download folder with Google Drive API
Edit - example downloading a folder
String destinationFolder = "/tmp/downloadedfiles/";
List<File> files = result.getFiles();
File newFile;
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
String fileId = file.getId();
String fileName = file.getName();
OutputStream outputstream = new FileOutputStream(destinationFolder + fileName);
service.files().get(fileId)
.executeMediaAndDownloadTo(outputstream);
outputstream.flush();
outputstream.close();
}
}

Where i Can find text file created by servlet in Eclipse

This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.

How to save , read and write files in android in external storage?

I'm trying to understand how to work with files in Android
I have installed my android application in external storage
it contain a folder dataof files that it need while running...
firstly I think that my folder will saved automatically in the sdcard while installing
but after reading some question here , It seem I should create a folder in which I save my
folder data...
I write this question to ask about steps to do to achieve my goal an I need your advances
Goal
Save a folder data in external storage , read from it and write a new file
Steps
add permission to manifest file
create a folder in sdcard ==> how to place my folder there ?
create a new file , save it on sdcard and write into it
code
This is a part of my activity :
{
....
File file = new File ("...")
doPrediction(file);
}
private void doPrediction (String FileName)
{
for (File child : VisualModels.listFiles()) {
svmPredict.run(MyDataSource.inputPrediction,
new File( MyDataSource.outputPrediction+ "/"+child.getName()+".predict"),
child);
}
}
I declared the class svmPredict as any ordinary java class ans this is the code of run method
try
{
BufferedReader input = new BufferedReader(new FileReader(inputFile));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
svm_model model = new svm().svm_load_model(modelFile);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
svm_predict.info("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
Please read the Android documentation regarding External Storage.
Pay attention to the getExternalFilesDir(). You can retrieve the path to the external storage using this method.
When you have the path, you can use the File object to create the data folder on the external storage like this:
File dataDirectory = new File(getExternalFilesDir() + "/data/");
Then create the folder by applying the mkdirs()-method on the File object:
dataDirectory.mkdirs();
To write to external storage, you will indeed have to declare this in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Get a file given a path to the file

I want to get a file which i saved in a specific directory on my phone.
How can I find and get a ref to it so I can do with it something different like uploading to a server?
Thanks in advance.
Shiran
Well where do you store your file?
Store the file in a specific area such as
Environment.getExternalStorageDirectory()
Then when you want to read it, just use the file name used and the path obtained from the above method.
File f = new File("location");
Remember, if you're trying to access the sd card you need to set permissions. Then just handle the "file" in whatever way it is you're trying to do something.
If you're looking to use the SDCard check this post:
Permission to write to the SD card
[Edit - Example]
String filenameToWrite = "Test.jpg"
try{
File f = new File(Environment.getExternalStorageDirectory() + "/Photos/");
if (f.exists()){
File fileToWrite = new File(Environment.getExternalStorageDirectory() + "/Photos/" + filenameToWrite;
// Do something to write file, save bitmap, save byte stream, etc.
}
} catch(IOException e){
Log.e("File", "Could not save file, error occured: " + e.toString());
}
Here's a few getting started tutorials to help you understand how to read and write files in java. This (apart from the 'path') is a java question, not an Android one.
Tutorials:
http://beginwithjava.blogspot.com/2011/04/java-file-save-and-file-load-objects.html
http://www.roseindia.net/java/beginners/java-write-to-file.shtml

What is my directory when writing files in Android?

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();
When trying to delete one of those files, this is what I use, but it's returning false.
String tag = v.getTag().toString();
File file = new File(System.getProperty("user.dir")+"/"+tag);
String s = new Boolean (file.exists()).toString();
Toast.makeText(getApplicationContext(), s, 1500).show();
file.delete();
How can I overcome this problem?
Use getFileStreamPath(FILENAME) to find your file. From the docs:
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Your current working directory.
To help diagnose the problem, use file.getAbsolutePath() to see the full path.
It could also be a permissions problem, if you're trying to delete from another application. If so, you may need to change to MODE_WORLD_WRITEABLE (insecure), or restructure your code so the create and delete are called by the same app.
EDIT: That was mostly incorrect. I didn't realize that openFileOutput didn't use the current working directory.
Use same contents as 'FILENAME' variable in your first snippet in the second snippet while trying to delete.
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Video";
File RootFile = new File(RootDir);
RootFile.mkdir();
FileOutputStream f = new FileOutputStream(new File(RootFile, "Sample.mp4"));
i used this code to save the video files to non-default location. Hope this will be useful to you.By default it is storing in sd card
For each application the Android system creates a "data/data/package of the application" directory.
Files are saved in the "files" folder under this directory
to change the default directory the above code will be used
the default working directory can be displayed using fileobject.getAbsolutePath()

Categories