欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

通过File类获取文件信息,未封装,求封装成类,file封装,package com.

来源: javaer 分享于  点击 20064 次 点评:30

通过File类获取文件信息,未封装,求封装成类,file封装,package com.


package com.taoniwu.io;import java.io.*;public class TestFile {    /**     * @param args     */    public static void main(String[] args) throws IOException {        File f;        //键盘输入 字符串赋给sr        InputStreamReader in = new InputStreamReader(System.in);        BufferedReader buf = new BufferedReader(in);        String sr = null;        try {            System.out.print("请输入文件路径:");            sr = buf.readLine();        } catch (Exception e) {            System.out.println(e + "输入错误");            System.exit(-1);        }        //判断文件或文件路径是否存在,存在则创建File对象        try {            if (sr.length() > 0) {                f = new File(sr);                if(f.exists()){                    info(f);                }                else{                    System.out.println("这不是一个文件或文件夹路径!");                }            }        } catch (Exception e) {            System.out.println(e + "运行错误");        }    }    //info方法,输出文件或文件夹信息    public static void info(File f) throws IOException{        //判断路径是文件还是文件夹        String sw;        long leng = 0;        if(f.isDirectory()){            sw = "文件夹";            leng = 0;        }        else{            sw = "文件";            leng = f.length();        }        System.out.println(sw+"名字:"+f.getName());        System.out.println(sw+"路径:"+f.getPath());        System.out.println(sw+"是否可读:"+(f.canRead()?"可读":"不可读"));        System.out.println(sw+"是否可写:"+(f.canWrite()?"可写":"不可写"));        //判断文件长度是否为0        System.out.println(sw+"长度为:"+(leng == 0?"文件长度为0或为文件夹":leng));    }}//该片段来自于http://byrx.net
相关栏目:

用户点评