I have a couple of methods which take filenames as parameters. My doubt is that what is better way to declare the parameters of these methods.
Should the parameter be of type String
void normalizeData(String inFile)
Or should I explicitly declare the parameter as File
.
void normalizeData(File inFile)
Personally I find File
more intuitive but want to know about what is the best practice for such things.
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading.
Yes you can. You might get a null pointer, if the new File() call generates an exception.
How to create a File Object? A File object is created by passing in a string that represents the name of a file, a String, or another File object. For example, File a = new File("/usr/local/bin/geeks");
I would pass an java.io.InputStream
- this makes the code easier to test and doesn't bind it to the file system.
This way your code ends up like:
public void normalizeData(InputStream in)
{
...
}
And calling it:
myObject.normalizeData(new FileInputStream(myFile));
Or
myObject.normalizeData(new FileInputStream("c:/myfile.txt"));
Or in a test
myObject.normalizeData(new ByteArrayInputStream("some test data".getBytes()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With