0

Is there any way to get valid/existing parent from provided path without looping.

My requirement is to create folder at provided path and i want to add validation that that folder have write permission.

So I added below code. but issue is some time path of getParent is not exists

Files.isWritable(Paths.get(path).getParent())

Example

"C:\MyFolder\Test" is existing folder.

Case1:
path=C:\MyFolder\Test\a 
Paths.get(path).getParent() will be C:\MyFolder\Test 
Files.isWritable will be true/false based on permission of "C:\MyFolder\Test".

Case2:
path=C:\MyFolder\Test\a\b\c 
Paths.get(path).getParent() will be C:\MyFolder\Test\a\b 
Files.isWritable will be always false.

I can add loop like getParent() till exists and then verify Files.isWritable(). Is there any better solution to get valid/existing path.

Krupa
  • 457
  • 3
  • 14
  • can you add a ternary if? – Pushkar Adhikari Mar 13 '19 at 06:08
  • Yes, i created recursive function with ternary if. – Krupa Mar 13 '19 at 06:14
  • extra information from [javadocs](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isWritable(java.nio.file.Path)) **Note that result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for writing will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.** – Pushkar Adhikari Mar 13 '19 at 06:16
  • also, please check [How can you work out why FIles.isWritable() returns false on Windows](https://stackoverflow.com/questions/35082228/how-can-you-work-out-why-files-iswritable-returns-false-on-windows) – Pushkar Adhikari Mar 13 '19 at 06:21
  • Okay, Is there any other way to add validation like does i have folder creation permission or not? or can i add such validation on exception class? – Krupa Mar 13 '19 at 06:24

1 Answers1

1

You can try using createDirectories if you also want the parent directories to be created. Certainly, you'd have to extract parent directory path as you are doing it already if it's a file.

you can also optionally refer this SO answer, for the old-school way without java.nio package.

Do use a try-catch to handle in case the directory creation fails.