0

How to solve this?

    File f=new File("d:/tester.txt");
    long size=f.length();  // returns the size in bytes
    char buff[]=new char[size]; // line of ERROR
                // will not accept long in it's argument
                // I can't do the casting (loss of data)

Is it possible to use size as the length of buff without the loss of data?

If yes how can i use it?

My second question is :

Why i am not getting the actual number of bytes?

This is the program :

import java.io.*;
class tester {
 public static void main(String args[]) {
 File f=new File("c:/windows/system32/drivers/etc/hosts.File");
 long x=f.length();  // returns the number of bytes read from the file
 System.out.println("long-> " + x );
}

}

The output is long-> 0 ,but obviously it is not so.Why do i get this result?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

3

You need to cast the long to an int

char buff[]=new char[(int) size];

This will only work for files less than 2 GB in size.

However, if you intend to use this to read the file perhaps you meant

byte[] buff=new byte[(int) size];

I would look at FileUtils and IOUtils from Apache Commons IO which has lots of help methods.


I doubt you have a file with that name. perhaps you need to drop the .File at the end which sounds like an odd extension.

I would check f.exists() first.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • For files larger than 2 GB (actually 100 MB is large enough to avoid), I wouldn't read them all at once. You should read them a block (for binary) or line (for text) at a time. Your hosts files should be much smaller than this. – Peter Lawrey May 26 '11 at 06:36
  • 1
    @ Peter Lawrey but i have a file named `hosts` with extension `.File` – Suhail Gupta May 26 '11 at 06:42
  • @Suhail Gupta I think you're confusing the *Type* of file with the file extension. Try it without the extension. – Zach L May 26 '11 at 06:49
  • 1
    @ Zach L `can you tell me the difference.` yes i have tried without the extension and it works. – Suhail Gupta May 26 '11 at 06:52
  • 1
    I have never heard of an extension called `.File` and I have been using MS-DOS/Windows since version 2.0. What would be the point of calling a file a `.File` Isn't it a file already? – Peter Lawrey May 26 '11 at 06:53
  • 1
    @Suhail Gupta Windows Explorer displays a column with the header Type, that I suspect you were looking at. That is Windows' description of the file (for example, SomeDocument.doc might have the Type "Word Document"). An extension is the last part of a file name, after and including the last dot in the name (for example, SomeDocument.doc has the extension .doc). Files (like the `hosts` file you were getting the length of) do not always need extensions. – Zach L May 26 '11 at 07:00