JAVA IO

1.编码

gbk编码:中文占2个字节,英文占1个字节

utf-8编码:中文占3个字节,英文占1个字节

utf-16be编码:中文占2个字节,英文占2个字节


2.File类

File类只用于表示文件(目录)的信息(大小、名称等),不能用于文件内容的访问

3种分隔符写法:

File file = new File("D:" + File.separator + "test");

File file = new File("D:\\test");

File file = new File("D:/test");

file.mkdir();//创建目录(不能创建多级目录)

file.mkdirs();//创建多级目录

file.createNewFile();//创建文件

遍历目录文件

public class FileUtils {
	public static void listDirectory(File dir)throws IOException{
		if(!dir.exists()){
			throw new IllegalArgumentException("目录:"+dir+"不存在!");
		}
		
		if(!dir.isDirectory()){
			throw new IllegalArgumentException(dir+"不是目录!");
		}
	
		/*String[] files = dir.list();
		for (String file : files) {
			System.out.println(file);
		}*/
		
		File[] files = dir.listFiles();
		for (File file : files) {
			if(file.isDirectory()){
				listDirectory(file);
			}else{
				System.out.println(file);
			}
		}
	}
}
RandomAccessFile java提供的对文件内容的访问,既可以读文件,也可以写文件
RandomAccessFile支持随机访问文件

FileInputStream
public class IOUtil {
	/**
	 * 单字节读取不适合大文件,效率很低
	 * @param fileName
	 * @throws IOException
	 */
	public static void printHex(String fileName) throws IOException {
		InputStream in = new FileInputStream(fileName);
		int b;
		int i = 1;
		while ((b = in.read()) != -1) {
			if (b <= 0xf) {
				System.out.print("0");
			}
			System.out.print(Integer.toHexString(b) + " ");
			if (i++ % 10 == 0)
				System.out.println();
		}
		in.close();
	}
	/**
	 * 批量读取,对大文件而言效率高
	 * @param fileName
	 * @throws IOException
	 */
	public static void printHexByByte(String fileName) throws IOException {
		InputStream in = new FileInputStream(fileName);
		byte[] buf = new byte[1024];
		int count = 1;
		int bytes;
		while ((bytes = in.read(buf, 0, buf.length)) != -1) {
			for (int i = 0; i < bytes; i++) {
				if (buf[i] <= 0xf) {
					System.out.print("0");
				}
				System.out.print(Integer.toHexString(buf[i] & 0xff) + " ");
				if (count++ % 10 == 0)
					System.out.println();
			}
		}
		in.close();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值