Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

determining size of a file from classpath ???

 
Jeffrey Pony
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9319
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Jeffrey Pony
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9319
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic