java文件基本操作函数

对文件操作是软件工程师在日常开发过程操作比较的一些操作下面有针对性的给大家介绍一下java对文件的基本操

作函数。

1.File()

要想操作文件需要先建立文件对象。

基本格式:

File file=new File(文件路径);

 

2.exists()判断文件是否存在

String fpath="g:/test.txt";//原来无此文件
File file=new File(fpath);
System.out.println(file.exists()); //输出false;

 

3.createNewFile() 创建新文件
说明:如果文件已经存在则不创建,并且返回false,如果文件不存在则创建,并且返回true;

String fpath="g:/test.txt";//原来无此文件
File file=new File(fpath);
System.out.println(file.exists()); //输出false;
try {
    System.out.println(file.createNewFile());
    } catch (IOException e) {
    e.printStackTrace();
    }
System.out.println(file.exists()); //因为已经创建了输出true;

 

4.canRead()判断文件是否可读

String fpath="g:/test.txt";//原来无此文件
File file=new File(fpath);
System.out.println(file.exists()); //输出false;
try {
    System.out.println(file.createNewFile());
    } catch (IOException e) {
    e.printStackTrace();
    }
System.out.println(file.canRead());

 

更多内容请查看:59biye网

猜你喜欢

转载自benben.iteye.com/blog/2016353
今日推荐