Java 判断文件大小

Python012

Java 判断文件大小,第1张

public static void main(String[] args) {

File file = new File("D:/201709201336160.05V")

getFileSize(file)

}

/**

* 获取文件大小

* @param file

*/

public static void getFileSize(File file) {

FileInputStream fis = null

try {

if(file.exists() &&file.isFile()){

String fileName = file.getName()

fis = new FileInputStream(file)

System.out.println("文件"+fileName+"的大小是:"+fis.available()+"\n")

}

} catch (Exception e) {

e.printStackTrace()

}finally{

if(null!=fis){

try {

fis.close()

} catch (IOException e) {

e.printStackTrace()

}

}

}

}

这个可以判断大小 输出的是byte 你转化一下MB就行了

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("此文件不存在")

        }

    }

import java.net.*

import java.io.*

public class URLConnectionDemo{

    public static void main(String[] args)throws Exception{

        URL url = new URL("http://www.scp.edu.cn/pantoschoolzz/BG/Bord/Message/DownloadMessageAttachment.aspx?ID=215")

        URLConnection uc = url.openConnection()

        String fileName = uc.getHeaderField(6)

        fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8")

        System.out.println("文件名为:"+fileName)

        System.out.println("文件大小:"+(uc.getContentLength()/1024)+"KB")

        String path = "D:"+File.separator+fileName

        FileOutputStream os = new FileOutputStream(path)

        InputStream is = uc.getInputStream()

        byte[] b = new byte[1024]

        int len = 0

        while((len=is.read(b))!=-1){

            os.write(b,0,len)

        }

        os.close()

        is.close()

        System.out.println("下载成功,文件保存在:"+path)

    }

}