Error when reading a Pdf file from internal memory? - java

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.

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.

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.

How to check that file is opened by another process in Java? [duplicate]

I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File package and there is a canWrite() method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?
Using the Apache Commons IO library...
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)
This whole issue is fraught with portability issues and race conditions:
You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.
A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.
Notes:
If you use the Files API instead of the File API you will get more information in the event of a failure.
On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using
fileIsLocked = !file.renameTo(file)
most useful, as it avoids false positives when processing write protected (or readonly) files.
org.apache.commons.io.FileUtils.touch(yourFile) doesn't check if your file is open or not. Instead, it changes the timestamp of the file to the current time.
I used IOException and it works just fine:
try
{
String filePath = "C:\sheet.xlsx";
FileWriter fw = new FileWriter(filePath );
}
catch (IOException e)
{
System.out.println("File is open");
}
I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.
You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.
Hi I really hope this helps.
I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.
try{
Files.move(Paths.get(currentFile.getPath()),
Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
// DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
} catch (Exception e){
// DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
}
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.

Unable to write to the Internal Storage

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.

How can I return the file path using the JNLP file chooser

Hi I am trying to get the returned file path by my JNLP file chooser. Here's my code.
I don't know how and where to get the file path. is it from fileContents? fileConents.getfilepath something like that?
try {
if (fileOpenService==null) {
fileOpenService = (FileOpenService)ServiceManager.
lookup("javax.jnlp.FileOpenService");
}
fileContents = fileOpenService.openFileDialog(path, xtns);
} catch(UnavailableServiceException use) {
use.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
Thanks in advance!
According to http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
You can call other methods on the File object, such as
getPath, isDirectory, or exists to obtain information about the file.
You can also call other methods such as delete and rename to change
the file in some way. Of course, you might also want to open or save
the file by using one of the reader or writer classes provided by the
Java platform. See Basic I/O for information about using readers and
writers to read and write data to the file system.
It is for security reasons that a FileContents will not return a path. The JRE asked the user if our app. could access the content of that file, not it's path.
It is a bit like the brower/HTML based file upload field. Some browsers provide the entire path, while more typically it is just the content/name.

Categories