Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better - using String or File as parameter type for methods that take filenames [closed]

Tags:

java

file-io

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.

like image 358
MoveFast Avatar asked Jun 17 '13 07:06

MoveFast


People also ask

Can we have same method name with different parameters?

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.

Can you return a file in Java?

Yes you can. You might get a null pointer, if the new File() call generates an exception.

How do I make a file object a default directory?

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");


1 Answers

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()));
like image 169
Nick Holt Avatar answered Oct 31 '22 01:10

Nick Holt