• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

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
 
Normally trees don't drive trucks. Does this tiny ad have a license?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic