问题描述
如何解决呢?
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)
是否可以将size
用作buff
的长度而不会丢失数据?
如果可以,我该如何使用?
我的第二个问题是:
为什么我没有得到实际的字节数?
这是程序:
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 );
}
}
输出是long-> 0
,但显然不是。为什么我得到这个结果?
解决方法
您需要将long转换为int
char buff[]=new char[(int) size];
这仅适用于小于2 GB的文件。
但是,如果您打算使用它来读取文件,则可能是您的意思。
byte[] buff=new byte[(int) size];
我将看看Apache Commons IO的FileUtils和IOUtils,它具有许多帮助方法。
我怀疑您是否有该名称的文件。也许您需要在末尾丢掉ѭ7,听起来像是个奇怪的扩展。
我先去检查f.exists()
。