- 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://www.codesnippet.cn/detail/070820135015.html
来源: http://www.codesnippet.cn/detail/070820135015.html