用java代码如何查看本地一个文件的大小

Python018

用java代码如何查看本地一个文件的大小,第1张

public static void getFileSize(String path){

        //传入文件路径

        File file = new File(path)

        //测试此文件是否存在

        if(file.exists()){

            //如果是文件夹

            //这里只检测了文件夹中第一层 如果有需要 可以继续递归检测

            if(file.isDirectory()){

                int size = 0

                for(File zf : file.listFiles()){

                    if(zf.isDirectory()) continue

                    size += zf.length()

                }

                System.out.println("文件夹 "+file.getName()+" Size: "+(size/1024f)+"kb")

            }else{

                System.out.println(file.getName()+" Size: "+(file.length()/1024f)+"kb")

            }

        //如果文件不存在

        }else{

            System.out.println("此文件不存在")

        }

    }

android中的java获取文件大小的方法:

import java.io.File

import java.io.FileInputStream

import java.io.FileReader

import java.io.IOException

public class FileContent {

private String path = "F:\\下载说明.txt"

public FileContent() throws IOException

{

File f = new File(path)

FileReader fileReader = new FileReader(f)

BufferedReader br = new BufferedReader(fileReader)

String str

while((str = br.readLine() ) != null)

{

System.out.println(str)

}

System.out.println(new FileInputStream(new File(path)).available() / 1024 / 1024 +"M")

}

public static void main(String[] args) {

try {

new FileContent()

} catch (IOException e) {

e.printStackTrace()

}

}

}

你好,这边有一个示例代码,希望对你有所帮助。示例中的urlString,你可以下载之后看看是否跟打印信息大小一致。我这边是一致的。

p:所导入的包都是java.net下面的。

main方法中 直接调用这个函数即可。

static  int getNetWorkFile( ){

   String  urlString="https://img-blog.csdn.net/20180323154952670?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0p1c3RDbGltYmluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70"

    int length=0

    URL url

    try {

        url = new  URL(urlString)

        HttpURLConnection urlcon=(HttpURLConnection)url.openConnection()//打开连接

        //根据响应获取文件大小

        length=urlcon.getContentLength()

        urlcon.disconnect()//关闭连接

    } catch (Exception e) {    

        e.printStackTrace()

    }

    System.out.println(length)

    return length

}