JAVA文件操作基础

闲来无事,想做一个小小的即时网络聊天工具,这就涉及到JAVA网络编程。而网络编程又是以一系列的I/O操作为基础的,还会涉及到诸如加密算法、多线程等领域。

此篇文章记述我在学习文件操作时所练代码,代码如下:

import java.io.File;
public class IOTest {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) {
		//Create file object
		File f1 = new File("d:\\test");
		File f2 = new File("1.txt");
		File f3 = new File("f:\\file.txt");
		File f4 = new File ("d:\\","1.txt");
		//Create files
		try {
			boolean b = f3.createNewFile();
		}catch(Exception e) {
			e.printStackTrace();
		}
		//Judge if the file exist
		System.out.println(f4.exists());
		//Get absolute path
		System.out.println(f3.getAbsolutePath());
		//Get file name
		System.out.println(f3.getName());
		//Get parent directory
		System.out.println(f3.getParent());
		//Judge if it is a directory
		System.out.println(f1.isDirectory());
		//Judge if it is a file
		System.out.println(f3.isFile());
		//Get file length
		System.out.println(f3.length());
		//Get all files and directories' names under current directory
		String[] s = f1.list();
		for (int i = 0; i < s.length; i++){
			System.out.println(s[i]);
		}
		//Get file object
		File[] f5 = f1.listFiles();
		for (int i = 0; i < f5.length; i++){
			System.out.println("f" + f5[i]);
		}
		//create directory
		File f6 = new File("f:\\test\\abc");
		boolean b1 = f6.mkdir();
		System.out.println(b1);
		b1 = f6.mkdirs();
		//Rename file
		File f7 = new File("f:\\a.txt");
		boolean b2 = f3.renameTo(f7);
		System.out.println(b2);
		//Set read only
		f7.setReadOnly();
		
	}

}


 下面这部分是文件的名称打印和删除操作,由于无法直接删除一个非空目录,所以删除非空目录需要先删除其目录下的所有子目录,这就涉及到一个递归遍历问题,代码如下:

 

import java.io.File;
public class AdvanceFileDemo {

	/**
	 * Advanced file operation demo
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File f = new File("f:\\Book");
		printAllFile(f);
		File f1 = new File("d:\\test");
		deleteAll(f1);
	}

	/**
	 * print all the directories and files under current directory
	 * @param f File object
	 */

	public static void printAllFile (File f) {
		//Print current file name
		System.out.println(f.getName());
		//If it is a directory
		if (f.isDirectory()) {
			//Get all sub-directories and files
			File [] f1 = f.listFiles();
			
			int len  = f1.length;
			for (int i = 0; i < len; i++) {
				printAllFile(f1[i]);
			}
		}
	}
	
	/**
	 * Delete all files
	 * @param f File object
	 */
	public static void deleteAll (File f) {
		//If it is a single file
		if (f.isFile()) {
			f.delete();
		} else { 
			File f1[] = f.listFiles();
			int len  = f1.length;
			//delete sub-files
			for (int i = 0; i < len; i++) {
				deleteAll(f1[i]);
			}
			//delete current file
			f.delete();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值