---------------------- ASP.Net+Android+IO开发S、.Net培训、期待与您交流! ----------------------
File类概述
1、File类用来将文件或者文件夹封装成对象
2、方便对文件与文件夹属性信息进行操作
3、File对象可以作为参数传递给流的构造函数。
File类的常用方法
创建
1、boolean createNewFile():创建新文件,如果文件存在,返回false
2、boolean mkdir():创建目录,只能创建一级目录
3、boolean mkdirs():创建目录,可创建多级目录
删除
1、boolean delete():删除文件,如果文件不存在,返回false,如果删除的是目录,需要确保目录是空的
2、void deleteOnExit():程序结束时删除文件
判断
1、boolean exists():判断文件是否存在
2、boolean isFile():判断是否是一个文件
3、boolean isDirectory():判断是否是目录
4、boolean isHidden():判断文件是否隐藏
5、boolean isAbsolute():判断是否是绝对路径
6、boolean canExecute():判断文件可否执行
7、boolean canRead():判断文件是否可读
8、boolean canWrite():判断文件是否可写
获取信息
1、String getName():获取文件名
2、String getParent():获取文件路径
3、String getPath():获取封装进对象的路径
4、File getAbsoluteFile():获取绝对路径文件对象
5、String getAbsolutePath():获取绝对路径
6、long lastModified():获取最后修改时间
7、long length():获取大小
8、static File[] listRoots():静态方法,获取系统可用根目录
9、String[] list():获取目录中文件的文件名
10、String[] list(FilenameFilter filter):过滤文件名并获取
练习
1、列出d盘下的所有bmp后缀的图片
示例代码如下:
import java.io.*; public class Demo{ public static void main(String[] args){ listDemo(); } public static void listDemo(){ File dir=new File("d:\"); String[] arr=dir.list(new FilenameFilter(){ public boolean accept(File dir,String name){ return name.endsWith(".bmp"); } }); } }
2、用递归的方式列出d盘下所有文件
示例代码如下:
import java.io.*; public class Demo{ public static void main(String[] args){ File dir = new File("D:\"); showDir(dir); } public static void showDir(File dir){ System.out.println(dir.getName()); File [] files = dir.listFiles(); for (int x= 0 ; x<files.length;x++ ){ if(files[x].isDirectory()) showDir(files[x]); else System.out.println(files[x]); } } }
Properties类
概述
Properties 是 Hashtable 的子类,
也就是说它具备Map集合的特点,而且它里面存储的键值对都是字符串
它是集合中和IO技术相结合的集合容器
该对象 特点:可以用于键值对形式的配置文件。
那么在加载数据时候,需要数据有固定格式:键=值
常用方法
1、String getProperty(String key):通过key获取value信息
2、void load(InputStream inStream):从字节流加载键值对信息
3、void load(Reader reader):从字符流加载键值对信息
4、Object setProperty(String key, String value):设置键值对信息
5、void store(OutputStream out, String comments):将键值对信息导入到字节流
6、void store(Writer writer, String comments):对键值对信息导入到字符流
配置文件的代码示例
import java.util.* import java.io.*; public class Demo{ public static void main(String[] args) throws IOException{ Properties prop=new Properties(); File file=new File("count.ini"); if(!file.exists()) file.createNewFile(); FileInputStream fis=new FileInputStream(file); prop.load(fis); int count=0; String value=prop.getProperty("time"); if(value!=null){ count=Integer.parseInt(value); if(count>=5){ System.out.println("使用次数已到!"); return ; } } count++; prop.setProperty("time",count+""); FileOutputStream fos=new FileOutputStream(file); prop.stroe(fos,""); fis.close(); fos.close(); } }
打印流PrintWriter和PrintStream
可以直接操作输入流和文件。
代码示例如下:
import java.io.*; public class Demo{ public static void printWriterMethod() throws IOException{ BufferedReader bufr =new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out,true); String line = null; while( (line = bufr.readLine()) != null){ if("over".equals(line)) break; out.println(line.toUpperCase()); } out.close(); bufr.close(); } }
合并流SequenceInputStream
对多个流进行合并
示例代码如下:
import java.io.*; import java.util.*; public class Demo{ 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> en=v.elements(); SequenceInputStream sis=new SequenceInputStream(en); 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); } fos.close(); sis.close(); } }
切割流
示例代码如下:
import java.io.*; import java.util.*; public class Demo{ public static void main(String[] args) throws IOException{ FileInputStream fis=new FileInputStream("1.bmp"); FileOutputStream fos=null; byte[] buf=new byte[1024*1024]; int len=0; int count=1; while((len=fis.read(buf))!=-1){ fos=new FileOutputStream((count++)+".part"); fos.write(buf,0,len); fos.close(); } fis.close(); } }
对象的序列化
将对象存储到硬盘上,叫做对象的持久化存储。
想要对对象进行序列化,该对象必须实现Serializable接口,Serializable接口没有方法,称为标记接口。
示例代码如下:
import java.io.*; 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; } } public class Demo{ public static void main(String[] args) throws Exception{ writeObj(); readObj(); } public static void writeObj() throws Exception{ ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("obj.txt")); oos.writeObject(new Person("wangda",30,"cn")); oos.close(); } public static void readObj() throws Exception{ ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.txt")); Person p=(Person)ois.readObject(); System.out.println(p); ois.close(); } }
管道流
输入输出可同时进行,结合多线程使用。
import java.io.*; class Read implements Runnable{ private PipedInputStream in; Read(PipedInputStream in){ this.in=in; } public void run(){ try{ byte[] buf =new byte[1024]; System.out.println("读取前。。没有数据阻塞"); int len = in.read(buf); System.out.println("读到数据。。阻塞结束"); String data =new String(buf,0,len); System.out.println(data); in.close(); }catch (Exception e){ throw new RuntimeException("管道输入失败"); } } } class Write implements Runnable{ private PipedOutputStream out; Write(PipedOutputStream out){ this.out=out; } public void run(){ try{ System.out.println("数据写入,请等待"); Thread.sleep(6000); out.write("哥们来了".getBytes()); out.close(); }catch (Exception e){ throw new RuntimeException("管道输出失败"); } } } public class Demo{ 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(); } }
RandomAccessFile
随机访问文件,自身具备读写的方法。直接继承Object类,内部封装了字节输入输出流,同时封装了文件的指针,可对基本数据类型进行直接读写,最大的好处是可以实现数据的分段写入,通过seek方法。
示例代码如下:
import java.io.*; public class Demo{ public static void main(String[] args) throws Exception{ writeFile(); readFile() } public static void writeFile() throws Exception{ RandomAccessFile raf=new RandomAccessFile("1.txt","rw"); raf.write("李四".getBytes()); raf.write(25); raf.close(); } public static void readFile() throws Exception{ RandomAccessFile raf=new RandomAccessFile("1.txt","r"); raf.seek(8*2); byte[] buf=new byte[4]; raf.read(buf); String name=new String(buf); int age=raf.readInt(); System.out.println("name="+name); } }
操作基本数据类型的流对象DataStream
示例代码如下:
import java.io.*; public class Demo{ public static void main(String[] args) throws IOException{ writeData(); readData(); } public static void readData() throws IOException{ DataInputStream dis=new DataInputStream(new FileInputStream("data.txt")); int num=dis.readInt(); boolean b=dis.readBoolean(); double d=dis.readDouble(); System.out.println(num); System.out.println(b); System.out.println(d); dis.close(); } public static void writeData() throws IOException{ DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.txt")); dos.writeInt(234); dos.writeBoolean(true); dos.writeDouble(111.234); dos.close(); } }
三类操作基本数据类型的IO流
操作字节数组
ByteArrayInputStream与ByteArrayOutputStream
操作字符数组
CharArrayReader与CharArrayWrite
操作字符串
StringReader 与 StringWriter
字符编码
操作字符编码的最常用流对象是InputStreamReader和OutputStreamWriter,可以任意指定编码表进行解码转换
常用的编码表
ASCII:美国标准信息交换码。用一个字节的7位可以表示。
ISO8859-1:拉丁码表。欧洲码表,用一个字节的8位表示。
GB2312:中国的中文编码表。
GBK:中国的中文编码表升级,融合了更多的中文文字符号。
Unicode:国际标准码,融合了多种文字。所有文字都用两个字节来表示,Java语言使用的就是unicode
UTF-8:最多用三个字节来表示一个字符
示例代码如下:
import java.io.*; public class Demo{ public static void main(String[] args) throws IOException{ writeText(); readText(); } public static void writeText() throws IOException{ OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("utf.txt"),"UFT-8"); osw.write("你好"); osw.close(); } public static void readText() throws IOException{ InputStreamReader isr=new InputStreamReader(new FileInputStream("uft.txt"),"UTF-8"); char[] buf=new char[10]; int len=isr.read(buf); String str=new String(buf,0,len); System.out.println(str); isr.close(); } }