Unable to write to the Internal Storage - java

Please have a look at the following code
File folder = new File("/Main Note/Sub Notes/"+dateStr+"/");
File file = new File(folder+name.getText().toString()+".txt");
try
{
if(!folder.exists())
{
folder.mkdirs();
}
FileOutputStream outputStream = openFileOutput(file.getName(),Context.MODE_WORLD_WRITEABLE);
outputStream.write(spokenText.getBytes());
outputStream.flush();
outputStream.close();
Toast.makeText(VoiceNotes.this, "Data Successfully written to: "+file.getAbsolutePath(), Toast.LENGTH_LONG).show();
}
catch(IOException io)
{
Toast.makeText(VoiceNotes.this, "Error in Writing to SD", Toast.LENGTH_LONG).show();
}
Here I am trying to write data to the internal memory. This has no errors, displays the data has been written successfully.
But when I navigate to the Internal SD in phone, I don't see any folder or file it created! I guess I have done something wrong, this is the first time I am writing to the internal storage in Android.

File folder = new File(context.getFilesDir(),"/MyFolder/");
files will be created in "/data/data/app.package/files/...". But you can see them only if device was rooted

You want to access the path returned by getExternalStorageDirectory() as described here.

Related

Android File Permissions issues on FilesDir()

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.

Android Studio - Read-Only Filesystem?

I am trying to write a file to internal device storage on my phone (and on user's phones in the future). I was watching a video tutorial from 2016 (https://www.youtube.com/watch?v=EhBBWVydcH8) which shows how he writes output to a file very simply. If you want to see his code, skip forward to 8:23.
Anyway, I basically tried his code, then since that didn't work, I figured would search around.
Apparently, to create a file, I need these lines of code:
String filename = "textfile.txt";
File file = new File(filename);
file.mkdirs();
file.createNewFile();
On the second line, file.createNewFile(), I get the below error:
java.io.IOException: Read-only file system
at java.io.UnixFileSystem.createFileExclusivel
at java.io.UnixFileSystem.createFileExclusivel
at java.io.File.createNewFile(File.java:948)
etc......
And then, if I run my code just by using the lines of code from the tutorial, I get a Null pointer.
Code:
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(IDNum.getBytes());
fos.close();
System.out.println("Wrote STuff Outputtt?");
} catch (Exception e) {
e.printStackTrace();
}
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:199)
at com.lecconnect.lockoutdemo.FileManager.AddUser(FileManager.java:37)
Line 37 is the first line in the try/catch.
Please let me know if you require any additional information to assist me. Your replies are greatly appreciated.
It is important to separate the directory and the file itself.
In your code, you call mkdirs on the file you want to write, which is incorrect usage because mkdirs makes your file into a directory. You should call mkdirs for the directory only, so it will be created if it does not exist, and the file will be created automatically when you create a new FileOutputStream object for this file.
Try this one:
File directory = getFilesDir(); //or getExternalFilesDir(null); for external storage
File file = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(IDNum.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}

Can't Find Created File - Needs Root Privileges?

My app downloads a file to my Android tablet. I can see the file on my tablet, but I can't find the file using my computer's file manager.
A response to another Stack Overflow question says the file manager may need "root privileges," but I don't know how to give a file manager root privileges or download a file manager that has root privileges. Is that possible? A second answer to that same question mentions some way to transfer the file using the command line, but I haven't been able to figure out how to do that.
I need to be able to transfer the file to my computer. What is the easiest way to do this?
void newFile() {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "file.txt");
FileOutputStream fos = new FileOutputStream(file);
String myInputText = "I really hope this works!";
fos.write(myInputText.getBytes());
fos.close();
System.out.println("My file is at " + file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
If you familiar with Linux Operating system, that you can use command line to chmod the file privilege. But I think if you can move this file in your tablet, maybe try to transfer it by Blue tooth, email is much easier.

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

Error when reading a Pdf file from internal memory?

I am trying to read a pdf file from internal memory of the device my code is here:
File pdfFile;
pdfFile=new File("data/data/com.myapp.main/app_c"+md+"/c"+md+".pdf");
if(pdfFile.exists())
{
try{
FileOutputStream fileOutput = openFileOutput(pdfFile.toString(), Context.MODE_WORLD_READABLE);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(ChTable.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
But the Pdf reader shows an Error -File not supported-Or File Not found .But I have checked that file is there at this location.I have also changed the permission to the file ,but still the same result. Would Someone help me detect and solve my problem ?
you can use PDFBox library to read data from pdf -
http://pdfbox.apache.org/
data/data/com.myapp.main/app_c"+md+"/c"+md+".pdf"
Is this path correct?
I am guessing the path should be like below.
data/data/com/myapp/main/app_c"+md+"/c"+md+".pdf"
You should be using one of the apis to get the application's files directory rather than assuming what the path will be.
Your actual problem however is most likely that any file you create there is probably private to the owning application, so the PDF reader app lacks permission to access it.
Solutions to that would be to change the file mode to world readable, or more commonly to put the file on the external storage (ie, "sdcard") rather than the internal memory, as that does not (to date) have a concept of permissions. Though it's worth remembering that a device isn't guaranteed to have an external storage, or for it to be accessible at any given point in time even if it exists.

Categories