We help IT Professionals succeed at work.

How to resolve path traversal issue in java

srikotesh
srikotesh asked
on
Hi Experts,

//Path Traversal Issue
				
String configuration = path +File.separator+"data"+File.separator+temp+File.separator+id+type+"."+frmt;
File newFilePath = new File(configuration);

Open in new window


please suggest how to change the above to resolve path traversal issue.
Comment
Watch Question

Top Expert 2016

Commented:
You don't usually want to do string concatenation adding in File.separator values to build a path.

File filePath = new File(folder, file)

or

File folderPath = new File(parent, child)

will let you assemble a path out of elements, without adding together pieces using File.separator

Doug
Top Expert 2016

Commented:
That is of course true. But that will only help when you have condensed your tokens, which will require concatenation. You should probably log debug the result of the concatenation such that the reasons for any surprises are instantly visible
Commented:
You could use
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html#get-java.lang.String-java.lang.String...-   
File newFile = Paths.get(path, "data", temp,id, type + "." + frmt).toFile();

Open in new window

Top Expert 2016

Commented:
Ah well done - wasn't familiar with that

Commented:
@CEHJ, thank you.