java中讲讲File的用法,举例?

本文深入讲解Java中File类的使用方法,包括如何创建文件实例、获取文件名、路径及绝对路径,以及检查文件是否存在。通过具体示例代码,帮助读者理解File类在文件操作中的作用。

2.1 File的用法 

马 克-to-win:sun公司设计File类,本身不能用来读数据或写数据。(要想读写数据,必须和其它io流的类配合使用,比如 FileInputStream等)File类的功能就是对磁盘上的文件或目录做一些非读写方面的工作,比如看看文件在哪个目录,哪天创建的,创建个新空 文件等。

例:2.1.1
import java.io.*;
public class TestMark_to_win {

    public static void main(String args[]) throws Exception {
/*File(String parent, String child) Creates a new File instance from a
parent pathname string and a child pathname string.the parent  pathname is taken to denote a directory, and the child pathname string is taken to denote either a directory or a file.  */
        File f1 = new File("c:\\tmp", "tmp\\1.txt");
 //File f1=new File("1.txt");
/*getName就是lastname*/
        System.out.println("getName is " + f1.getName());
/* getPath Returns: The string form of this abstract pathname。即原样返回。 */
        System.out.println("getPath is" + f1.getPath());
/* getAbsolutePath: Returns the absolute pathname string of this
abstract pathname. If this abstract pathname is already absolute,
then the pathname string is simply returned as if by the getPath()
method.if you use File f1=new File("1.txt"); you can see the
difference.结果会变成
getName is 1.txt
getPath is1.txt
Absolute Path is D:\eclipseJee\t1\1.txt
not */
        System.out.println("Absolute Path is " + f1.getAbsolutePath());
        System.out.println(f1.exists() ? "exist" : "not");
    }
}
 

更多请见:http://www.mark-to-win.com/tutorial/java_8_UsageOfFile.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值