I want to check for the given folder path(local path,shared path) and credentials for the folder, whether user has access to this folder.
In windows, we can verify that by manually by right click on that folder and go to security tab.
I read some posts, but most of them are suggesting to create a file in that folder and then delete it to verify it. I am restricted to do that in my requirement.
please help me if we can do that it in java
Create a new file with the given path:
File testFile = new File("path");
If canRead:
if(file.canRead()) {
// do something
}
For a complete list of what you can do with java.io.File, please visit the API (you can try/catch to delete, write, etc):
http://docs.oracle.com/javase/6/docs/api/java/io/File.html
The File class has several useful methods to achieve what you want:
File file = new File("path-to-file");
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getParent());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isHidden());
For more info, try using the official docs: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
EDIT
As per OP's comment, here's a way to check a file's owner and the file's permissions:
Path path = FileSystems.getDefault().getPath("path");
UserPrincipal owner = null;
Set<PosixFilePermission> posixFilePermissions = null;
try {
owner = Files.getOwner(path);
posixFilePermissions = Files.getPosixFilePermissions(path);
} catch (IOException ex) {
Logger.getLogger(TestCenter.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(owner);
System.out.println(posixFilePermissions);
Output (the file has 664 permission on my Linux machine):
victor
[OWNER_WRITE, OWNER_READ, OTHERS_READ, GROUP_WRITE, GROUP_READ]
Related
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.
I am trying to get the following code to work properly. It always prints the output from the catch block, even though the output that is only printed if the file exists, is printed.
String outputFile = "/home/picImg.jpg";
File outFile = new File(outputFile);
if(outFile.exists)
newStatus(" File does indeed exist");
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
fos.write(response);
fos.close();
return outputFile;
} catch (FileNotFoundException ex) {
newStatus("Error: Couldn't find local picture!");
return null;
}
In the code response is a byte[] containig a .jpg image from a URL. Overall I am trying to download an image from a URL and save it to the local file system and return the path. I think the issue has to do with read/write permissions within /home/. I chose to write the file there because I'm lazy and didn't want to find the username to find the path /home/USER/Documents. I think I need to do this now.
I notice in the terminal I can do cd ~ and get to /home/USER/. Is there a "path shortcut" I can use within the file name so that I can read/write in a folder that has those permissions?
No. The ~ is expanded by the shell. In Java File.exists() is a method, you can use File.separatorChar and you can get a user's home folder with System property "user.home" like
String outputFile = System.getProperty("user.home") + File.separatorChar
+ "picImg.jpg";
File outFile = new File(outputFile);
if (outFile.exists())
Edit
Also, as #StephenP notes below, you might also use File(File parent, String child) to construct the File
File outFile = new File(System.getProperty("user.home"), "picImg.jpg");
if (outFile.exists())
~ expansion is a function of your shell and means nothing special for the file system. Look for Java System Properties "user.home"
Java provides a System property to get the user home directory: System.getProperty("user.home");.
The advantage of this is, that it works for every operating system that can run the Java virtual machine.
More about System properties: Link.
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.
I have read all the other questions related to this in StackOverflow and I did not find any clear response.
To cut it short, I have an application that will store some files in a directory that I will use than to process them. I have intentions of moving my app in different places (other computers) so I need to have a relative path to work with so that I will not change that in each time.
Does anyone know how to get the relative path of the application (not the full path) so that I could use in this case? If what I am asking is not wright please tell me another way to achieve what I need. Thank you
Just use "./".
No matter what directory your application has been launched from, "./" will always return that directory.
For example:
new File("./") will return a file object pointed at the directory your java application has been launched from
new File("./myDirectory") will return a file object pointed at the myDirectory folder located in the directory your java application has been launched from
Here is one approach:
I believe you need to define the path of directory containing the files in a configuration/property file. You can change the path in the configuration file when you move your application or the directory containing the file. This is how your properties file(let's say config.properties) contents should be:
filesDirPath=\usr\home\test
And this what you should do in the code:
private void readConfig()
{
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
//get the directory path property value
String flesDirPath = prop.getProperty("filesDirPath");
System.out.println("Files to be read are located in dir : " + flesDirPath );
} catch (IOException ex) {
ex.printStackTrace();
}
}
I am trying to remove a file in java, but it will not remove. Could someone explain why it won't remove?
Here is the code that I am using:
File bellFile = new File("config\\normbells.txt");
bellFile.delete();
File bellFileNew = new File("config\\normbells.txt");
bellFileNew.createNewFile();
System.out.println("Done!");
NOTE: I am trying to wipe the file, if that helps.
File deletion can fail under the following circumstances:
The file does not exist.
The file is a directory not a file.
You don't have access to delete the file.
You don't have access to the the file or any of its parent directory.
The file is being used currently by some another application.
Try avoiding all the above mentioned circumstances & you'll surely able to delete the file.
Also before deleting the file add this condition :
if (file.exists()) {
file.delete();
}
Java7 has new functionality for this.
Path target = Paths.get("D:\\Backup\\MyStuff.txt");
Files.delete(target);
Path newtarget = Paths.get("D:\\Backup\\MyStuff.txt");
Set<PosixFilePermission> perms
= PosixFilePermissions.fromString("rw-rw-rw-");
FileAttribute<Set<PosixFilePermission>> attr
= PosixFilePermissions.asFileAttribute(perms);
Files.createFile(newtarget, attr);
Take a look at the File class http://docs.oracle.com/javase/7/docs/api/java/io/File.html
File bellFile = new File("config\\normbells.txt");
if(bellFile.delete())
{
System.out.println("Done!");
}