黑马程序员_IO流2

  ------- android培训java培训、期待与您交流! ----------


一    File类、文件类

1 java将文件进行描述封装,方便对文件进行操作

2 方法摘要:
createNewFile()  创建文件不存在,返回true。如果文件存在则不创建,返回false
mkdir()  创建一级文件目录
mkdirs() 创建多级文件目录
delete()  删除文件
deleteOnExit()  退出时删除
exists()  判断文件是否存在
isFile()  判断是否文件
isDirectory()  判断是否目录
isAbsolute()   判断是否绝对路径
getName() 获取名称
getPath()  获取封装路径
getAbsolutePath()  获取绝对路径
getParent() 获取父目录
length () 获取文件大小
renameTo()  改文件名
list()  获取文件包含的文件及目录,返回一个字符串数组
listFiles()  获取文件包含的文件及目录,返回一个文件数组

3 递归:定义一个函数,在函数调用自己。必须要有结束条件。

4 例子:

//例子:将一个目录下的图片文件的绝对路径存到一个文件上
//需要用到递归,集合,IO流
import java.io.*;
import java.util.*;
class  Demo
{
	public static void main(String[] args) throws IOException
	{
		File file=new File("d:\\javacx");//创建一个文件对象
		List<File> list=new ArrayList<File>();//创建一个集合存储文件
		fileToList(file,list);//调用功能将文件存到集合中
		String filename="a.txt";//定义一个文件名称
		listToFile(list,filename);//将集合中的文件的绝对路径通过流写到文件中
		

	}
	//定义一个功能将集中的文件的绝对路径存到一个文件中
	public static void listToFile(List<File> list,String filename) throws IOException
	{
		//定义字符写入流
		BufferedWriter bufw=new BufferedWriter(new FileWriter(filename));
		//遍历集合的文件
		for(File file:list)
		{
			//获取文件的绝对路径并写到流中
			bufw.write(file.getAbsolutePath());
			bufw.newLine();//换行
			bufw.flush();//刷新
		}
		bufw.close();//关闭流资源
	}
	//定义一个功能将指定目录中的.jpg文件存进集合
	public static void fileToList(File file,List<File> list)
	{
		//将目录下的文件变成文件数组
		File[] files=file.listFiles();
		//遍历文件数组
		for(File f: files)
		{
			//判断文件是否是目录,是的话就递归
			if (f.isDirectory())
			{
				fileToList(f,list);
			}
			//不是的话就把文件存进集合中
			else
			{
				//获取文件名称,并判断名称的后缀名
				String name=f.getName();
				if(name.endsWith(".jpg"))
					list.add(f);
			}
		}
	}
}


二    Properties

1 概述
(1)Properties是HashTable的子类,拥有HashTable的特性
(2)Properties是与IO流相结合的集合容器,用于键值对形式的配置文件,并且存储的全是字符串

2 方法摘要:
setProperty(String key,String values)  添加元素,键值都是字符串
getProperty(String key)  通过键获取值
stringPropertyNames()  获取键集合
load(InputStream)  将流中的数据加载到集合
store(OutputStream,"")  将集合中的数据加载到流中

3 例子:定义一个限定运行次数的程序,次数一到,就给出提示并结束程序。

代码:

/*思路:
1 创建集合
2 创建流
3 加载流中数据进集合
4 取出数据进行判断,再自增
5 创建写入流加载集合中的数据
*/
import java.io.*;
import java.util.*;
class  RunCountDemo
{
	public static void main(String[] args) throws IOException
	{
		//创建能与流关联的集合
		Properties prop=new Properties();
		File file=new File("count.txt");
		//判断文件是否存在,没有的话就创建该文件
		if(!file.exists())
			file.createNewFile();
		//创建读取流与文件相关联
		FileReader fr=new FileReader(file);
		//加载流中的数据进集合
		prop.load(fr);
		int count=0;//定义一个计数器
		//获取time所对应的值
		String values=prop.getProperty("time");
		if(values!=null)
		{
			//将值转化为基本数据类型进行判断
			count=Integer.parseInt(values);
			if(count>=5)
			{
				//如果次数满足条件,给出提示并结束程序
				System.out.println("用户体验次数已到,请注册用户");
				return;
			}
		}
		count++;//计数器自增
		prop.setProperty("time",count+"");//将新的键值对存进集合
		//定义一个写入流并与文件相关联
		FileWriter fw=new FileWriter(file);
		//将集合的数据存进与流相关联的文件中
		prop.store(fw,"");
	}
}


三    打印流
1特点:可以将各种数据类型的数据原样打印

2 PrintStream,字节打印流
(1)其构造函数能接受的参数:File对象、String、字节输出流(OutputStream)

3 PrintWriter,字符打印流
(1)其构造函数能接受的参数:File对象、String、字节输出流(OutputStream)、字符输出流(Writer)
例子:读取键盘录入字符串,将其大写打印在控制台上。
代码:

import java.io.*;
class PrintDemo 
{
	public static void main(String[] args) throws IOException
	{
		//获取键盘录入
		BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
		//定义字符打印流,构造函数能接受字节输出流.并且自动刷新
		PrintWriter pw=new PrintWriter(System.out,true);
		//读取键盘录入
		String line=null;
		while ((line=bufr.readLine())!=null)
		{
			//判断结束标志
			if("over".equals(line))
				break;
			//将读到的数据变成大小打印出来
			pw.println(line.toUpperCase());
		}
		bufr.close();
		pw.close();
	}
}

四    管道流
1 管道流,与多线程相结合。PipedInputStream和PipedOutputStream相连。一个线程负责输入,一个线程负责输出。
2 例子:

import java.io.*;
//定义一个线程用于管道读取流读取数据
class Read implements Runnable
{
	private PipedInputStream pi;
	Read(PipedInputStream pi)
	{
		this.pi = pi;
	}
	//覆盖run()方法
	public void run()
	{
		try
		{
			//定义一个数组接收数据
			byte[] buf = new byte[1024];
			//读取数据
			int len = pi.read(buf);
			//打印读到的数据
			System.out.println(new String(buf,0,len));
			//关闭资源
			pi.close();
		}
		catch (IOException e)
		{
			throw new RuntimeException("管道读取流失败");
		}
	}
}
//定义一个线程用于管道输出流写出数据
class Write implements Runnable
{
	private PipedOutputStream po;
	Write(PipedOutputStream po)
	{
		this.po = po;
	}
	public void run()
	{
		try
		{
			//写数据
			po.write("cheng gong fa song".getBytes());
			//关闭资源
			po.close();
		}
		catch (Exception e)
		{
			throw new RuntimeException("管道输出流失败");
		}
	}
}

class  PipedDemo
{
	public static void main(String[] args) throws IOException
	{
		//创建管道字节输入流
		PipedInputStream pi = new PipedInputStream();
		//创建管道字节输出流
		PipedOutputStream po = new PipedOutputStream();
		//管道字节输入流连接管道字节输出流
		pi.connect(po);
		//创建线程并执行线程,输入流负责读,输出流负责写
		new Thread(new Read(pi)).start();
		new Thread(new Write(po)).start();
	}
}

五    RandomAccessFile、随机访问文件

1 该类不是IO体系中的子类,直接继承Object

2 内部封装了输入流和输出流,同时具备读和写功能,可以读写基本数据类型。并且只能操作文件。

3 内部封装了一个数组,可以通过指针操作数组

4 可以通过getFilePointer方法获取指针位置,通过seek方法设置指针位置。

5 构造函数:RandomAccessFile(String name, String mode) 
(1)构造函数可以指定模式r只读,rw读写
(2)如果模式为只读r,则不会创建文件,会去读取一个已存在的文件,如果文件不存在,会抛出异常
(3)如果模式为读写rw,文件不存在则会创建,文件存在也不会覆盖文件
(4)方法摘要:
writeInt(int i)  写一个四个字节的整数
readInt(int i)   读一个四个字节的整数
seek(int i) 设置指针位置
skipBytes(int i)  跳过i个字节

(5)例子演示:

import java.io.*;
class  RandomAccessFileDemo
{
	public static void main(String[] args) throws IOException
	{
		//write();
		read();
	}
	//定义一个功能演示读取字节
	public static void read() throws IOException
	{
		//创建RandomAccessFile对象,模式为只读
		RandomAccessFile raf=new RandomAccessFile("Random.txt","r");
		//设置指针位置从24的位置开始读
		raf.seek(8*3);
		//读取数据
		byte[] buf=new byte[4];
		raf.read(buf);
		String name=new String(buf);
		int len=raf.readInt();
		//打印数据
		System.out.println(name+len);
		raf.close();//关闭资源
	}
	//定义一个功能演示写入字节
	public static void write() throws IOException
	{
		//创建RandomAccessFile对象,模式为读写
		RandomAccessFile raf=new RandomAccessFile("Random.txt","rw");
		//写入数据,张三占四个字节。int数据类型占四个字节
		raf.write("张三".getBytes());
		raf.writeInt(15);
		//设置指针位置为24,再开始写入数据
		raf.seek(8*3);
		raf.write("李四".getBytes());
		raf.writeInt(16);
		//关闭资源
		raf.close();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值