黑马程序员学习日记--IO流技术(二)

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

一:File对象和常用方法

File类: 

用来将文件或者文件夹封装成对象

方便对文件和文件夹的属性信息进行操作

File对象可以作为参数传递给流的构造函数

File类中的常用方法:

1,创建

boolean createNewFile( )

(在指定的位置创建文件,如果该文件已经存在,则不创建,返回false)

boolean mkdir():创建文件夹

boolean mkdirs():创建多级文件夹

2,删除

boolean delete():删除失败返回false

void deleteOnExit():在程序退出时删除指定文件

3,判断

boolean exists():文件是否存在

isDirectory():

isFile()

isHidden()

isAbsolute()

4,获取信息

getName()

getPath()

getParent()

getAbsolute()

long lastModified()

long length()

练习代码:

//File对象功能
import java.io.*;
class J20_1 
{
	public static void main(String[] args) throws IOException
	{
		//consMethod();
		//method_1();
		//method_2();
		//method_3();
		//method_4();
		method_5();
	}
	static void sop(Object obj)
	{
		System.out.println(obj);
	}
	static void consMethod() throws IOException
	{
		File f1 = new File("a.txt");
		File f2 = new File("D:","c.txt");
		File d = new File("D:");
		File f3 = new File(d,"c.txt");
		sop("f1="+f1);
		sop("f2="+f2);
		sop("f3="+f3);
	}
	static void method_1() throws IOException
	{
		File f = new File("a.txt");
		//sop("create:"+f.createNewFile());
		sop("delete:"+f.delete());
	}
	static void method_2() throws IOException
	{
		File dir = new File("aaa\\bbb\\ccc\\ddd");
		//sop("execute:"+f.canExecute());
		//sop("exist:"+f.exists());
		sop("dirmake:"+dir.mkdirs());
	}
	static void method_3() throws IOException
	{
		File f = new File("D:\\file.txt");
		//f.createNewFile();
		//f.mkdir();
		sop("ifFile:"+f.isFile());
		sop("ifDirectory:"+f.isDirectory());
		sop("isAbsolute:"+f.isAbsolute());
	}
	static void method_4() throws IOException
	{
		File f = new File("D:\\file.txt");
		//f.createNewFile();
		sop("path:"+f.getPath());
		sop("absolutePath:"+f.getAbsolutePath());
		sop("parent:"+f.getParent());
	}
	static void method_5() throws IOException
	{
		File f1 = new File("a.txt");
		File f2 = new File("b.txt");
		sop("rename:"+f2.renameTo(f1));

	}
}

二:递归

递归:函数自身调用自身

注意:

1,限定条件

2,递归的次数,要避免内存溢出

练习代码:

/*
练习:
将一个指定目录下的java文件的绝对路径,存储到一个文本文件中
建立一个java文件列表文件

思路:
1:对指定的目录进行递归
2:获取递归过程中java文件的路径
3:将这些路径存储到集合中
4:将集合中的数据写入文件
*/
import java.util.*;
import java.io.*;
class J20_5 
{
	public static void main(String[] args) throws IOException
	{
		File file = new File("E:\\demo");
		List<File> list = new ArrayList<File>();
		fileToList(file,list);
		System.out.println(list.size());
		File f1 = new File("D:\\javalist.txt");
		writeToFile(list,f1);
	}
	static void fileToList(File file,List<File> list)
	{
		File[] files = file.listFiles();
		for(File f:files)
		{
			if(f.isDirectory())
				fileToList(f,list);
			else if(f.getName().endsWith(".java"))
				list.add(f);
		}
	}
	static void writeToFile(List<File> list,File file)
	{
		BufferedWriter bw = null;
		try
		{
			bw = new BufferedWriter(
			new FileWriter(file));
			for(File f:list)
			{
				bw.write(f.getAbsolutePath());
				bw.newLine();
				bw.flush();
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException();
		}
		finally
		{
			if(bw!=null)
				try
				{
					bw.close();
				}
				catch (IOException e)
			{
				throw new RuntimeException();
			}
		}
		
	}
}

三:Properties

Properties是hashtable 的子类

是集合中和IO技术相结合的集合容器

特点:可用于键值对形式的配置文件中

练习代码:

/*
练习:
记录应用程序运行次数
如果使用次数已到,那么给出注册提示
*/
import java.io.*;
import java.util.*;
class J20_7 
{
	public static void main(String[] args) throws IOException
	{
		Properties prop = new Properties();
		File file = new File("count.ini");
		file.createNewFile();
		FileInputStream fis = new FileInputStream(file);
		int count = 0;
		prop.load(fis);
		String time = prop.getProperty("time");
		if(!(time==null))
		{
			count = Integer.parseInt(time);
			if(count>=5)
			{
				System.out.println("使用次数已到,请去官网注册");
				return;
			}
		}
		count++;
		prop.setProperty("time",count+"");
		FileOutputStream fos = new FileOutputStream("count.ini");
		prop.store(fos,"");
		fis.close();
		fos.close();
	}
}

四:打印流 ,序列流,操作对象

打印流:

PrintWriter与PrintStream

可以直接操作输出流和文件,该流提供了打印方法,可以将各种数据类型的数据都原样打印

PrintStream构造函数可接受的参数类型:

1,file对象 File

2,字符串路径 String

3,字符输出流 OutputStream

PrintWriter构造函数可以接受的参数类型:

1,file对象 File

2,字符串路径 String

3,字符输出流 OutputStream

4,字符输出流 Writer

练习代码:

import java.io.*;
class J20_8 
{
	public static void main(String[] args) throws IOException 
	{
		BufferedReader br = new BufferedReader(
			new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);
		String line = null;
		while((line=br.readLine())!=null)
		{
			if(line.equals("over"))
				break;
			out.println(line.toUpperCase());
			//out.flush();
		}
		br.close();
		out.close();
	}
}


序列流:

SequenceInputStream  对多个流进行合并

练习代码:

import java.util.*;
import java.io.*;
class J20_9 
{
	public static void main(String[] args)  throws IOException
	{
		Vector<FileInputStream> v = new Vector<FileInputStream>();
		v.add(new FileInputStream("1.txt"));
		v.add(new FileInputStream("2.txt"));
		v.add(new FileInputStream("3.txt"));
		Enumeration<FileInputStream> e = v.elements();
		SequenceInputStream sis = new SequenceInputStream(e);
		FileOutputStream fos = new FileOutputStream("4.txt");
		byte[] buf = new byte[1024];
		int len = 0;
		while((len=sis.read(buf))!=-1)
		{
			fos.write(buf,0,len);
		}
		sis.close();
		fos.close();
	}
}


操作对象:

ObjectinputStream和ObjectOutputStream

被操作的对象需要实现Serializable(标记接口)

练习代码:

import java.io.*;
class J21_1 
{
	public static void main(String[] args) throws Exception
	{
		writeDemo();
		readDemo();
	}
	static void readDemo() throws Exception
	{
		ObjectInputStream ois = new ObjectInputStream(
			new FileInputStream("out.txt"));
		Person p = (Person)ois.readObject();
		System.out.println(p);
	}
	static void writeDemo() throws IOException
	{
		ObjectOutputStream oos = new ObjectOutputStream(
			new FileOutputStream("out.txt"));
		Person p = new Person("hoop",25,"kr");
		oos.writeObject(p);
		oos.close();
	}
}
class Person implements Serializable
{
	public static final long serialVersionUID = 42L;
	private String name;
	transient int age;
	static String country = "CN";
	Person(String name,int age,String country)
	{
		this.name = name;
		this.age = age;
		this.country = country;
	}
	public String toString()
	{
		return name+"..."+age+"..."+country;
	}
}


五:管道流

PipedInputStream和PipedOutputStream

输入输出可以直接进行连接,通过结合线程使用

练习代码:

import java.io.*;
class J21_2 
{
	public static void main(String[] args) throws IOException
	{
		PipedInputStream pis = new PipedInputStream();
		PipedOutputStream pos = new PipedOutputStream();
		pis.connect(pos);
		Read r = new Read(pis);
		Write w = new Write(pos);
		new Thread(r).start();
		new Thread(w).start();
	}
}
class Read implements Runnable
{
	private PipedInputStream pis;
	Read(PipedInputStream pis)
	{
		this.pis = pis;
	}
	public void run()
	{
		try
		{
			byte[] buf = new byte[1024];
			int len = 0;
			System.out.println("读取数据,没有数据则阻塞");
			len = pis.read(buf);
			System.out.println("读取完毕");
			System.out.println(new String(buf,0,len));
			pis.close();
		}
		catch (IOException e)
		{
			throw new RuntimeException("管道读取流失败");
		}
		
	}
}
class Write implements Runnable
{
	private PipedOutputStream pos;
	Write(PipedOutputStream pos)
	{
		this.pos = pos;
	}
	public void run()
	{
		try
		{
			System.out.println("等待6秒后写入数据");
			Thread.sleep(6000);
			pos.write("piped come".getBytes());
			pos.close();
		}
		catch (Exception e)
		{
			throw new RuntimeException("管道输出流失败");
		}
		
	}
}


六:RandomAccessFile

IO包中成员,具备读和写功能

内部封装了一个数组,通过指针对数组的元素进行操作

可以通过getFilePointer获取指针位置

同时可以通过seek改变指针的位置

(该类只能操作文件,而且操作文件还有模式)

练习代码:

import java.io.*;
class J21_3 
{
	public static void main(String[] args) throws IOException 
	{
		//writeDemo();
		writeDemo_2();
		//readDemo();
	}
	static void readDemo() throws IOException
	{
		RandomAccessFile raf = new RandomAccessFile("raf.txt","r");
		byte[] buf = new byte[4];
		//raf.seek(8);
		raf.skipBytes(8);
		raf.read(buf);
		String s = new String(buf);
		System.out.println("name:"+s);
		int age = raf.readInt();
		System.out.println("age:"+age);
		raf.close();
	}
	static void writeDemo_2() throws IOException
	{
		File f = new File("raf.txt");
		RandomAccessFile raf = new RandomAccessFile(f,"rw");
		raf.seek(8*0);
		raf.write("周期".getBytes());
		raf.writeInt(101);
		raf.close();
	}
	static void writeDemo() throws IOException
	{
		File f = new File("raf.txt");
		RandomAccessFile raf = new RandomAccessFile(f,"rw");
		raf.write("张三".getBytes());
		raf.writeInt(97);
		raf.write("李四".getBytes());
		raf.writeInt(99);
		raf.close();
	}
}


七:操作基本数据类型,操作字节数组,操作字符数组,操作字符串

操作基本数据类型:

DataInputStream和DataOutputStream

练习代码:

import java.io.*;
class J21_4 
{
	public static void main(String[] args) throws IOException 
	{
		//readDemo();
		//writeDemo();
		//writeUTFDemo();
		readUTFDemo();
	}
	static void readUTFDemo() throws IOException
	{
		DataInputStream dis = new DataInputStream(
			new FileInputStream("UTFData.txt"));
		String s = dis.readUTF();
		System.out.println(s);
		dis.close();
	}
	static void writeUTFDemo() throws IOException
	{
		DataOutputStream dos = new DataOutputStream(
			new FileOutputStream("UTFData.txt"));
		dos.writeUTF("你好中国");
		dos.close();
	}
	static void readDemo() throws IOException
	{
		DataInputStream dis = new DataInputStream(
			new FileInputStream("data.txt"));
		int num = dis.readInt();
		Double d = dis.readDouble();
		boolean b = dis.readBoolean();
		System.out.println("num="+num);
		System.out.println("d="+d);
		System.out.println("b="+b);
		dis.close();
	}
	static void writeDemo() throws IOException
	{
		DataOutputStream dos = new DataOutputStream(
			new FileOutputStream("data.txt"));
		dos.writeInt(98);
		dos.writeDouble(983.762);
		dos.writeBoolean(true);
		dos.close();
	}
}


操作字节数组

ByteArrayInputStream:在构造时,需要接收数据源(字节数组)

ByteArrayOutputStream:在构造时,不用定义数据目的,内部封住了可变长度的字节数组

(两个流对象都操作的数组,没有使用系统资源)

练习代码:

import java.io.*;
class J21_5 
{
	public static void main(String[] args) 
	{
		ByteArrayInputStream bis = new ByteArrayInputStream("ABCDEFG".getBytes());
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		
		int by=0;
		while((by=bis.read())!=-1)
		{
			bos.write(by);
		}
		System.out.println(bos.size());
		System.out.println(bos.toString());
	}
}


操作字符数组

CharArrayReader和CharArrayWriter

操作字符串

StringReader和StringWriter


八:字符编码

字符流的出现为了方便操作字符,更重要的是加入了编码转换

通过子类转换流来完成:

InputStreamReader

OutputStreamWriter

(这两个对象构造的时候可以传入字符集)


常见的编码表:

ASCII:美国标准信息交换码

用一个字节的7位可以表示

ISO8859-1:拉丁吗表。欧洲码表

用一个字节的8位表示

GBK2312:中国的中文编码表

GBK:中国的中文编码表升级,融合了更多的中文文字符号

Unicode:国际标准吗,融合了多种文字

所有文字都用两个字节来表示,Java语言使用的是Unicode

UTF-8:做多用三个字节来表示一个字符


编码:字符串编程字节数组 str.getBytes( )

解码:字节数组编程字符串 new String(bytes[ ] )

练习代码:

/*
有五个学生,每个学生有三门课的成绩
从键盘输入以上数据(包括姓名,三门课程及)
输入的格式:如:zhangsan,30,40,60计算出总成绩
并把学生的信息和计算出的总分高低顺序存放在磁盘文件“stud。txt”中
*/
import java.io.*;
import java.util.*;
class J21_9 
{
	public static void main(String[] args) throws IOException
	{
		Comparator<Student> comp = Collections.reverseOrder();
		Set<Student> stus = Tool.getStu(comp);
		Tool.write2File(stus);
	}
}
class Student implements Comparable<Student>
{
	private String name;
	private int math,cn,en,sum;
	int getSum()
	{
		return sum;
	}
	String getName()
	{
		return name;
	}
	Student(String name,int math,int cn,int en)
	{
		this.name = name;
		this.math = math;
		this.cn = cn;
		this.en = en;
		sum = math+cn+en;
	}
	public int hashCode()
	{
		return name.hashCode()+sum*29;
	}
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Student))
			throw new ClassCastException();
		Student s = (Student)obj;
		return name.equals(s.name)&&sum==s.sum;
	}
	public String toString()
	{
		return "["+name+"]:"+math+","+cn+","+en;
	}
	public int compareTo(Student s)
	{
		int num = new Integer(this.sum).compareTo(new Integer(s.sum));
		if(num==0)
			return this.name.compareTo(s.name);
		return num;
	}
}
class Tool
{
	public static Set<Student> getStu() throws IOException
	{
		return getStu(null);
	}
	public static Set<Student> getStu(Comparator<Student> comp) throws IOException
	{
		BufferedReader bis = new BufferedReader(
			new InputStreamReader(System.in));
		String line = null;
		Set<Student> stus = null;
		if(comp==null)
			stus = new TreeSet<Student>();
		else
			stus = new TreeSet<Student>(comp);
		while((line=bis.readLine())!=null)
		{
			if(line.equals("over"))
				break;
			String[] arr = line.split(",");
			Student s = new Student(arr[0],
				Integer.parseInt(arr[1]),
				Integer.parseInt(arr[2]),
				Integer.parseInt(arr[3]));
			stus.add(s);
		}
		return stus;
	}
	public static void write2File(Set<Student> stus) throws IOException
	{
		BufferedWriter bw = new BufferedWriter(
			new FileWriter("stud.txt"));
		for(Student s : stus)
		{
			int sum = s.getSum();
			String line = s.toString();
			bw.write(line+"..sum="+sum);
			bw.newLine();
			bw.flush();
		}
		bw.close();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值