• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to retrieve file length in bytes using File class

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the code I am using to retrieve the file length.
But the retrieved file length was zero.
----------------- FileTest.java----------------------------------
package testexamples;
import java.io.*;
public class FileTest {
public static void main(String[] args){
File f = new File("C:\\My Documents");
if( f.isFile())
System.out.println("is a file\n");
else System.out.println("is not a file\n");
if( f.isDirectory()) {
System.out.println("is a directory\n");
String directory[] = f.list() ;
long size = 0;
for (int i = 0; i< directory.length; i++) {
File f1 = new File(directory[i]);
size = f1.length();
System.out.println(directory[i] + " " + size);
}
}
else {System.out.println("is not a directory");}
while(true);
}
}
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It looks like your problem is the use of the "new" keyword. What your are trying to do here is obtain a reference to each file in the directory. What you are actually doing is creating a new (empty) file for each existing file that is found. Try doing it this way and see if it works:
<PRE>
for (int i = 0; i< directory.length; i++) {
size = directory[i].length();
System.out.println(directory[i] + " " + size);
}
</PRE>
regards
Nick
reply
    Bookmark Topic Watch Topic
  • New Topic