Reputation: 21
Can any body explain this code? i am confused please guide me and explain this code easy wording in JSP language .Thanks
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("<h3>Uploaded Filename:</h3> "+fileName);
}
}
Upvotes: 0
Views: 158
Reputation: 10142
First refer documentation of methods - lastIndexOf
and substring
lastIndexOf & substring to understand what these methods do.
Also note that we use double slashes in code due to \
being escape character so \\
means single slash \
If you apply, lastIndexOf("\\")
, you might get either value -1
or >=0
. -1
value would mean that \
is not present in that String and value >=0
means that it is present.
In this below if part, you simply determine if \
is there in fileName
, if it is there - take only last portion and append with filePath
so for a fileName
with value like abc\test.txt
you are extracting only \test.txt
and appending to filePath
.
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}
Then , in else
part, we already know that \
is not present in so code is unnecessarily doing - fileName.lastIndexOf("\\")+1)
- this will always be zero.
else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
So code can simply be written as ,
else{
file = new File( filePath +fileName)}
line - new File(....)
creates a File
object that is where stream contents get written to.
On SO, these kind of questions don't get answered but I answered since your profile says that you are a student.
Secondly, I can't comment if that code is correct or incorrect, I simply explained what that code is doing.
Upvotes: 1
Reputation: 121
In java file path can be described by \\
.
For example: String path = "D:\\folder1\\folder2\\filename.type"
lastIndexOf("\\")
will return the last position value of \\
from your file name
.
The variable file
will be assigned the path
from which the file is going to be uploaded in the java program from your disk.
The if
and else
blocks check the file path is correct and it assigned the variable path
.
Finally write
method uploads the file from specified path.
Upvotes: 1