Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes I/O and Streams and the fly likes determining size of a file from classpath ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "determining size of a file from classpath ???" Watch "determining size of a file from classpath ???" New topic
Author

determining size of a file from classpath ???

Jeffrey Pony
Greenhorn

Joined: Jun 24, 2002
Posts: 25
I have to determine the length of the file present in the classpath to populate a byte array.

On reading from the classpath I get an InputStream and there is no method which exposes size of the file.

Iam currently doing something like this,


InputStream inputStream = this.getClass().getResourceAsStream("/my.txt");
byte[] fileContents = new byte[100];

try {
int read = inputStream.read(fileContents);
// byte[] fileContents = new byte[inputStream.available()];
String fullDate = new String(fileContents,0,read);
System.out.println("fullDate = " + fullDate);
} catch (IOException e) {
e.printStackTrace();
}

i.e. Currently the array fileContents is hardcoded and i want it to be set dynamically as per the size of the file.

I am not happy with this as inputStream.available() does not give the length.

Ideal thing would have been to do new File("filename.txt").length()
but this would require the file to be in the working directory and not classpath.

Thanks in advance.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8968
    
    9


would work. I would prefer to read a file into a ByteArrayOutputStream. It's a dynamically sized byte array so you don't need to know the file size beforehand.
Kudos for noticing that available() does not return file size. That was last week's Most Common Misconception.


[How To Ask Questions On JavaRanch]
Jeffrey Pony
Greenhorn

Joined: Jun 24, 2002
Posts: 25
Thanks for that.

Iam currently using JDK1.4 and could not find method
URI uri = url.toURI();

Also, how does one read a file into ByteArrayOutputStream / ByteArrayInputStream.
A code snippet would be great.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8968
    
    9

Originally posted by Jeffrey Pony:
Thanks for that.
I am currently using JDK1.4 and could not find method
URI uri = url.toURI();

Yea, it's a 1.5 thing. Try:



Also, how does one read a file into ByteArrayOutputStream / ByteArrayInputStream.
A code snippet would be great.

Read from an InputStream, write to a ByteArrayOutputStream. Continue until EOF.
You should read the Java Tutorial on IO. It may fill in some of the gaps you are struggling with.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: determining size of a file from classpath ???