Win a copy of Cloud Native PatternsE this week in the Cloud forum
or Natural Language Processing in the AI/ML forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

How to retrieve file length in bytes using File class

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!