user1993412
user1993412

Reputation: 862

Read a file in different directory by just specifying file name (via resource folder)

I am trying to implement a simple workaround for reading a file in a resource directory

My Folder structure is as below :

src 
| 
|------test 
|       |
|       -----com.tester.stackoverflow (package name)  
|                        | 
|                        ----BufferedExample.java
|------resources 
|        | -----com.tester.stackoverflow (package name)  
                         | ----Testing.txt

I am trying to read a file named "Testing.txt"

I have a common file utilty that is a different package altogether that read the file. (the code is scala)

package com.tester.utility

object FileHelper
{
  def read(file: File) : Array[Byte] =
  {
    val inputStream = new FileInputStream(file)
    try
    {
      val buffer = ListBuffer[Byte]()
      var bytes = inputStream.read()
      while (bytes != -1)
      {
        buffer.append(bytes.byteValue)
        bytes = inputStream.read()
      }
      buffer.toArray
    }
    catch
    {
      case ex: Exception =>
      {
        ex.printStackTrace
        throw ex
      }
    }
    finally
    {
      inputStream.close
    }
  }
}

The BufferedExample should read the file Testing.txt from the resource folder with the same package. Therefore , I am passing the file object object in my code above. But I am not able to locate the testing.txt file directly from the BufferedExample.java.

I really dont want to specify the file path in absolute manner. (passing only the file name).

Thanks !!!

Upvotes: 1

Views: 732

Answers (1)

jedison
jedison

Reputation: 976

If the resources directory is added to your classpath (for example in project definition in Eclipse or pom.xml), then you can use getResourceAsStream rather than new FileInputStream().
If you'd also like to get the package name from the current class, that is feasible as well, but a bit more complicated: this.getClass().getPackage().toString() or BufferedExample.class.getPackage().toString().
And then you can append the package name to the file name before saying getResourceAsStream.

Upvotes: 1

Related Questions