Java 中的 File 类

一、File 类

1、 java.io.File 类代表系统文件名(路径和文件名)。

2、 File 类的常见构造方法:

public File(String pathname)

以 pathname 为路径创建File对象,如果pathname是相对路径,则默认的当前路径在系统属性user.dir 中存储。

public File( String parent, String child )

以 parent 为父路径,child为子路径创建File对象。

3、 File的静态属性String separator 存储了当前系统的路径分隔符。(跨平台)


二、File 类常用方法

1、通过File对象可以访问文件的属性。

public boolean canRead( )

public boolean canWrite( )

public boolean exists( )

public boolean isDirectory( )

public boolean isFile( )

public boolean isHidden( )

public long lastModified( )

public long length( )

public String getName( )

public String getPath( )


2、通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)。

public boolean createNewFile ( ) throws IOException

public boolean delete ( )

public boolean mkdir ( )

public boolean mkdirs ( ) //创建在路径中的一系列目录

import java.io.*;
public class TestFile {
	public static void main(String[] args) {
		String separator = File.separator;
		String filename = "myfile.txt";
		String directory = "mydir1"+separator+"mydir2";
		File f = new File(directory,filename);
		if (f.exists()) {
			System.out.println("文件名: "+f.getAbsolutePath());
			System.out.println("文件大小: "+f.length());
		}else {
			f.getParentFile().mkdirs();
			try {
				f.createNewFile();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


树状列出文件结构:

import java.io.*;
public class Test {
	public static void main(String[] args) {
	String filepath = "C:/Users/Administrator/Desktop";
	String filename = "A";
	File f = new File(filepath,filename);
	int c = -1;
	DirectoryList(f,c);
	}
	
	public static void DirectoryList(File file,int c) {
		c += 1;
		StringBuffer s = new StringBuffer();
		for(int j = 0; j < c; j++) {
			s.append('	');
		}
		if(file.isDirectory()) {			                                    
			System.out.println(s+file.getName());
			File[] str = file.listFiles();
			for(int i = 0; i < str.length; i++) {
				DirectoryList(str[i],c);

			}
		}
		else {
			System.out.println(s+file.getName());
		}
	}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值