Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning 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
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic