Should the File class be used systematically when dealing with files or are there cases where it’s ok to use Strings to represent the path and filename?
Should the File class be used systematically when dealing with files or are there
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you take a look at the various file stream / reader / writer classes that take either a
StringorFile, you’ll see that the constructor that takes aStringis convenience overload for the constructor that takes aFile. In other words, theStringconstructor typically creates aFilefrom the pathname string and calls the other constructor.So using the
Fileversion potentially saves constructing new File objects.On the other hand, a
Fileinstance will occupy more memory than the equivalentString, and the cost of creating aFileinstance is small compared with the cost of opening and reading / writing a file.The bottom line is that it probably doesn’t matter for a small-scale application from a performance perspective. With a large scale application the most appropriate approach depends on what the application is actually doing; e.g. whether or not it is repeatedly using the same files.
And as the comments say, there are other ways to “denote” files / paths as well; e.g. “file:” URLs and the Java 7
Pathclass.