1、java file 获取文件大小 ,单位是kb,File.length()获得文件字节大小/1024 获得 KB数, 由于整数运算省略小数部分,故加1。
2、目前Java获取文件大小的方法有两种:
1)通过file的length()方法获取。
2)通过流式方法获取。
3、通过length方法:
1)创建一个文件。
2)获取文件大小。
3)查看结果。
import java.io.File
import java.io.RandomAccessFile
/**
* 2016年8月31日下午7:00:37
*
* @author 3306 TODO 计算字节数
*
*/
public class FileUtil {
public static void main(String[] args) {
String filePath = "d:/test.txt"// d盘必须存在test.txt文件
readEachLine(filePath)
}
/**
* 打印文件每一行的字节数
*
* @param filePath
* 文件路径
*/
private static void readEachLine(String filePath) {
try {
File file = new File(filePath)
if (file.exists()) {// 文件存在
RandomAccessFile accessFile = new RandomAccessFile(file, "r")// 只赋予读的权限
String line = ""
long lineIndex = 1
while (null != (line = accessFile.readLine())) {
System.out.println("line" + (lineIndex++) + ": " + line.getBytes().length)// 打印行号和字节数
}
accessFile.close()
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
java在使用字节输入流读取文本文件的时候,可以定义字节缓冲区,来实现高效的读取。如:FileinputStreamfis=newFileinputStream(path)byte[]buffer=newbyte[1024]//一次读取1024个字节然后通过fis.read(buffer)来将读取到的字节数保存在字节缓冲区中。