Java File 常用操作回顾

最近项目中要用到File这个类,温故而知新,回过头来回顾下这个File类,File类主要是对磁盘目录,文件进行操作的Api,具体其实查JDK api 的File全能获取到。

下面写一些文件目录的基本操作练习一下:


1. 列出文件目录和文件,文件随机访问

package com.dcz.io;

import java.io.File;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo {
	
	public static void main(String[] args) throws Exception {
		
		File dir = new File("E:\\迅雷下载");
		
		if(!dir.exists()){
			throw new IllegalAccessException("给定的目录不存在!");
		}
		
		if(!dir.isDirectory()){
			throw new IllegalAccessException("给定的不是一个目录");
		}
		
		File[] files = dir.listFiles();
		for(File f : files){
			if(f.isDirectory()){
				FileUtil.listDirectory(f);
			}else{
				System.out.println(f);
			}
		}
		
		// --------------------------------------------------------------
		
		
		// 创建目录
		File fileDir = new File("file");
		if(!fileDir.exists()){
			fileDir.mkdir();
		}
		// 创建文件
		File file = new File(fileDir, "abc.txt");
		if(!file.exists()){
			file.createNewFile();
		}
		
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
		
		// 读取文件指针【文件指针为:0】
		System.out.println("文件指针位置:" + randomAccessFile.getFilePointer());
		
		
		// 写字符(从API中可以查看到可以写很多类型的数据)
		randomAccessFile.write('a');
		
		// 读取文件指【文件指针为:1】
		System.out.println("文件指针位置:" + randomAccessFile.getFilePointer());
		
		// 写数字
		randomAccessFile.writeInt(12);
		
		// 读取文件指【文件指针为:5】
		System.out.println("文件指针位置:" + randomAccessFile.getFilePointer());
		
		// 写中文
		String str = "成长";
		byte[] strArray = str.getBytes("GBK");
		randomAccessFile.write(strArray);
		// 读取文件指【文件指针为:9】
		System.out.println("文件指针位置:" + randomAccessFile.getFilePointer());
		
		// 文件指针归零
		randomAccessFile.seek(0);
		
		// 创建缓冲
		byte[] buffer = new byte[(int)randomAccessFile.length()];
		// 读取文件内容
		randomAccessFile.read(buffer);
		
		String fileContent = new String(buffer, "gbk");
		
		// 打印文件内容
		System.out.println("文件内容是:" + fileContent);
		
		// 关闭
		randomAccessFile.close();
	}

}



 

posted @ 2015-09-05 18:47  dcz1001  阅读(150)  评论(0编辑  收藏  举报