黑马程序员系列第八篇 IO(2)

ASP.Net+Android+IOS开发  、Net培训、期待与您交流!

(前言:本篇文章主要依据毕向东老师的课程视频整理而成,如要详细学习,请观看毕老师视频  百度网盘链接地址:http://pan.baidu.com/s/1mgrkJWW)

 目录:1、File类       2、存储对象      3、RandomAccessFile类

 1、File类

File类  :将文件或文件夹封装成对象,方便对文件或文件夹的属性信息进行操作

File中Separator 字段是可跨平台的分隔符

对文件对象的基本操作,封装到了几个方法中演示

 1     //列出指定文件内文件及所以子文件信息
 2     public static void getAllFilesInfo(File file){
 3         //设置过滤条件,即搜索条件
 4         System.out.println(file);
 5         File[] files=file.listFiles();
 6         //打印信息
 7         for(int i=0;i<files.length;i++){
 8             if(files[i].isDirectory())
 9                 getAllFilesInfo(files[i]);
10             else System.out.println(files[i]);
11         }
12     }        
13     //列出指定文件内满足指定条件的文件信息
14     public static void getFilesFiltedInfo(File file){
15         //设置过滤条件,即搜索条件
16         File[] files=file.listFiles(new FilenameFilter(){
17             public boolean accept(File dir, String name){
18                 return name.endsWith(".Bin");
19             }
20         });
21         //打印信息
22         for(File fil:files)
23             System.out.println(fil.getName()+":"+fil.getTotalSpace());
24     }    
25     
26     //获取指定文件的信息
27     public static void getFileInfo(File file){
28         if(!file.exists())
29             System.out.println(file.getName()+" 文件不存在!!!");
30         else{
31         String absolutePath=file.getAbsolutePath();//获取绝对路径
32         String path=file.getPath();//获取相对路径
33         long time=file.lastModified();
34         long len=file.length();
35         String parent=file.getParent();//还回绝对路径下的父目录,如果获取的是相对路径则还回null
36         System.out.println("absolutePath:"+absolutePath+" path:"+path+" lastModifiedTime:"+time+" len"+len);
37         }
38     }
39     //列出系统文件信息
40     public static void listRoots(){
41         File[] files=File.listRoots();
42         for(File file:files)
43             System.out.println(file.getAbsolutePath()+file.getFreeSpace());
44     }

 2、存储对象    

需要将对象序列化持久化可存储化

没有方法的接口被称为标记接口    类的序列化值可以自己定义,否则由类自动生成

静态变量不能被序列化,非静态变量用transient修饰也可不被序列化

存储和读取对象的简单操作:

 1 public class IoTest {
 2 
 3     public static void main(String[] args) {
 4             //向文件中存储对象
 5              writeObject("D://Student.object",new Student("xujiax111",21));
 6              //从文件中读取对象
 7            //  readObject("D://Student.object");
 8     }
 9     public static void writeObject(String fileName,Object obj){
10         
11             ObjectOutputStream oos=null;
12         try {
13             //创建流资源
14             oos=new ObjectOutputStream(new FileOutputStream(fileName)) ;            
15                 oos.writeObject(obj);
16         } catch (FileNotFoundException e) {
17             e.printStackTrace();
18         } catch (IOException e) {
19             e.printStackTrace();
20         }finally{
21             try {
22                 if(oos!=null)
23                 oos.close();//关闭流资源
24             } catch (IOException e) {
25                 e.printStackTrace();
26             }
27         }
28     }
29     public static void readObject(String fileName){
30         //创建流资源
31            ObjectInputStream ois=null;
32         try {
33             ois=new ObjectInputStream(new FileInputStream(fileName));
34             System.out.println(ois.readObject());
35         } catch (FileNotFoundException e) {
36             e.printStackTrace();
37         } catch (IOException e) {
38             e.printStackTrace();
39         } catch (ClassNotFoundException e) {
40             e.printStackTrace();
41         }finally{
42                 try {
43                     if(ois!=null)
44                     ois.close();//关闭流资源
45                 } catch (IOException e) {
46                     e.printStackTrace();
47                 }
48         }
49     }
50 }
51 //常见一个student对象类,并对其实现序列化
52 class Student implements Serializable{
53 
54     private String name;
55     private int age;
56     
57     public Student(String name,int age){
58         this.name=name;
59         this.age=age;
60     }
61     public String toString(){
62         return name+":"+age;
63     }
64 }

 3、RandomAccessFile类

      java的RandomAccessFile提供对文件的读写功能,与普通的输入输出流不一样的是RamdomAccessFile可以任意的访问文件的任何地方。

     这就是“Random”的意义所在。

      RandomAccessFile的对象包含一个记录指针,用于标识当前流的读写位置,这个位置可以向前移动,也可以向后移动。

      RandomAccessFile包含两个方法来操作文件记录指针。

一个简单的向文件读写操作的代码示例:

 1 public class RandomAccessFileDemo {
 2 
 3     public static void main(String[] args) throws IOException {
 4 
 5           randomWriter();
 6           randomReader();
 7     }
 8     //向文件中写数据
 9     public static void randomWriter() throws IOException{
10         //创建对象
11         RandomAccessFile raf=new RandomAccessFile("D://randomAccess.txt","rw");
12         raf.seek(12*0);//设置指针位置,可以规定写的位置
13         raf.write("许佳".getBytes());
14         raf.writeInt(23);
15         raf.seek(12*1);
16         raf.write("许佳佳".getBytes());
17         raf.writeInt(24);
18         //关闭流资源
19         raf.close();
20     }
21     //向文件中读数据
22     public static void randomReader() throws IOException{
23         
24         RandomAccessFile raf=new RandomAccessFile("D://randomAccess.txt","rw");
25         raf.seek(12*0);//设置指针位置,可以规定读取的位置
26         byte[] bytes=new byte[8];        
27         raf.read(bytes);
28         String name=new String(bytes);
29         int age=raf.readInt();
30         //打印读取劫夺
31         System.out.println("name="+name+"::age="+age);
32         //关闭流资源
33         raf.close();
34     }
35 }

       初学者难免错误,欢迎评判指教,持续更正ing...........

ASP.Net+Android+IOS开发  、Net培训、期待与您交流!

原文地址:https://www.cnblogs.com/blueFlowers/p/4976861.html