JAVA IO——File文件的属性应用案例

1 java.io.File 

2 在Java中,File类是处理文件和目录路径的实用工具。它有许多方法,可以用来获取和处理文件或目录的属性。以下是一些常见的File类方法,您可以使用它们来获取文件的属性:

  1. getName():返回文件的名称。
  2. getParent():返回文件的基础路径。
  3. getPath():返回文件的完整路径。
  4. getAbsolutePath():返回文件的绝对路径。
  5. exists():检查文件或目录是否存在。
  6. isFile()isDirectory():检查File对象是否表示一个文件或目录。
  7. isDirectory():如果File对象表示一个目录,则返回true。
  8. isFile():如果File对象表示一个文件而不是目录,则返回true。
  9. lastModified():返回文件最后修改的日期和时间。
  10. length():返回文件的大小(以字节为单位)
package pb.io.file;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * 测试文件的属性
 * @author TerryZhong
 *
 */
public class FileInfo {

	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		System.out.print("请输入文件名:");
		StringBuffer buf=new StringBuffer();
		char ch;
		try {
			while((ch=(char)System.in.read())!='\n'){
				buf.append(ch);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		File file=new File(buf.toString().trim());//创建文件类对象
		if(file.exists()){//如果文件对象存在
			if(file.isFile()){//如果是文件
				System.out.println("文件名:"+file.getName().substring(0,file.getName().lastIndexOf('.')));//文件名
				System.out.println("路径:"+file.getPath());//文件路径
				System.out.println("绝对路径:"+file.getAbsolutePath());//文件绝对路径
				System.out.println("是否可读:"+file.canRead());//是否可读
				System.out.println("是否可写:"+file.canWrite());//是否可读
				System.out.println("文件长度:"+file.length()+"B");//文件长度
			}else
				System.out.println("不是文件!");
		}else
			System.out.println("文件没找到!");
		

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Terry谈企业数字化

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值