java基础教程--IO

来源:互联网 发布:长虹网络电视价格 编辑:程序博客网 时间:2024/04/30 01:48

java.io.File 类  代表文件,文件夹

  new File() 只是在内存堆创建对象,并不是在磁盘上创建文件夹、文件

  创建文件,文件夹有相应的方法

  文件系统操作:查看文件、文件夹的属性 、创建文件夹、文件

  列文件夹目录,删除文件夹、文件

  

RandomAccessFile随即访问文件,可以在任何位置开始读写文件

 

什么是文件:文件是byte by byte 的有序集合

每个byte 数据有位置序号  序号类型是long

文件模型

 文件数据    data  41 42 43 44  00 00 00 ff

 文件数据位置 index [0 1  2  3  4  5  6 7  8)

访问位置指针pointer  ^

 length = 8;

 

打开文件 方式:rw   r

文件打开默认位置在0

RandomAccessFile raf = newRandomAccessFile(filename,"rw")

写文件:raf.write(int b)

将参数b的低8位写到文件当前位置。每次写完自动移动指针到下个位置,准备下一次输入

如:b = 0x12121241(32位置) 低8位即是最后的41

 

读取文件:int b= raf.read()

 从文件的当前文治开始读取1个byte,将byte填充到int 的低8位,

 高24为保持0不变。如果读取到文件末尾返回0xffffffff(32个1) 

  每读取一个数据,文件指针自动后移



BR.java

public class BR {

     publicstatic void main(String[] args) throws Exception {

         FileInputStreamfis=new FileInputStream("/home/tarena/55.txt");

         InputStreamReaderisr=new InputStreamReader(fis,"GBK");

         BufferedReaderbr=new BufferedReader(isr);

         Stringstr;    

         while((str=br.readLine())!="-1"){System.out.println(str);}      

     }

}

 

Demo1.java

/**文件输出流掩饰

 * FileOutputStream

 * Output :输出,就是写出,向文件写出,写文件

 * Stream:流,长长的byte 序列,在流动

 */

public class Demo1 {

     public static void main(String[] args)throws IOException{

     //FileOutputStream构造器可以打开文件

     //如果文件不存在,会自动创建文件

     OutputStreamout = new FileOutputStream("out.dat",false);//true表示向旧文件添加,false表示覆盖

     out.write(0x41);     out.write(0x42);     out.write(0x43);     out.write(0x44);

     out.write(newbyte[]{0x45,0x46});      

     inti=0x1f12230e;//00011111 00010010 00100011 0000111

     intd1=i>>>24;//00000000 000000 00000000 00011111(1f)

     intd2=i>>>16;//00000000 00000000 00011111(00000000) 00010010(1f12)

     intd3=i>>>8;//00000000 00011111(00000000) 00010010(00000000)00100011(1f1223)

     intd4=i;//00011111(00000000) 00010010(00000000) 00100011(00000000) 0000111        

     out.write(d1);  out.write(d2);  out.write(d3);  out.write(d4);

     out.flush();//刷出缓存,尽可能的保证可靠写入文件      

     out.close();

     IOUtils.printHex("out.dat");

     }

}

 

Demo2.java

/*文件输入流

 * FileInputStream

 * Input :输入

 */

public class Demo2 {

     publicstatic void main(String[] args) throws IOException{

         InputStreamin =new FileInputStream("out.dat");

         intb=in.read();

         System.out.println(b);

         in.skip(5);//跳过5个数据

         intd1=in.read();    int d2=in.read();    int d3=in.read();    int d4=in.read();

         inti=(d1<<24)+(d2<<16)+(d3<<8)+d4;

         System.out.println(Integer.toHexString(i));

         System.out.println(Integer.toHexString(d1));

         System.out.println(Integer.toHexString(d2));

         System.out.println(Integer.toHexString(d3));

         System.out.println(Integer.toHexString(d4));

         System.out.println(Integer.toHexString(in.read()));      

         in.close();

     }

}

 

Demo3.java

public class Demo3 {

     publicstatic void main(String[] args) {

         byte[]bytes={-1,23,44,0x41};

         IOUtils.saveBytes(bytes,"bytes.dat");

         IOUtils.printHex("bytes.dat");      

     }

}

 

Demo4.java

public class Demo4 {

     publicstatic void main(String[] args) {

         byte[]bytes=IOUtils.saveBytes("out.dat");

         System.out.println(Arrays.toString(bytes));

         IOUtils.printHex(bytes);

     }

}

 

Demo5.java

public class Demo5 {

     publicstatic void main(String[] args) {

         IOUtils.copy("/home/tarena/sldfds","sdd");

         System.out.println("复制成功");

     }

}

 

FIFOS.java

public class FIFOS {

     publicstatic void main(String[] args) throws Exception{

         FileInputStreamfis= new FileInputStream("/home/tarena/slf/words.txt");

         FileOutputStreamfos= new FileOutputStream("/home/tarena/words.txt");       

         BufferedInputStreambis=new BufferedInputStream(fis);

         BufferedOutputStreambos=new BufferedOutputStream(fos);    

         intb;

         while((b=bis.read())!=-1){bos.write(b);}

         bos.flush();//将最后残留不够的文件写入,这个输出是一个byte一个byte输出的

         fis.close();     fos.close();    bis.close();    bos.close();//bos关闭之前会自动调用bos.flush的      

     }

}

 

IOUtils.java

/*

 * IO工具类

 * 递归删除子目录

 * 1 列出全部目录内容

 * 2 迭代全部内容

 * 3 如果是文件,删除之

 * 4 如果是目录,递归删除子目录

 * 5 迭代以后,当前目录是空的,删除当前目录

 */

public class IOUtils {

     //复制文件,将SRC复制为dst   

     publicstatic void copy(String src,String dst){

         try{

              InputStreamin = new FileInputStream(src);

              OutputStreamout = new FileOutputStream(dst);

              intcount;

              byte[]buf= new byte[1024*8];

              while((count=in.read(buf))!=-1){out.write(buf,0, count);}

              in.close(); out.close();

         }catch(IOExceptione){

              e.printStackTrace();thrownew RuntimeException(e);           

         }

     }   

     //将byte数组的全部数据写到文件中    

     publicstatic void saveBytes(byte[] bytes,String file){

         try{

              OutputStreamout=new FileOutputStream(file);

              out.write(bytes);out.close();

         }catch(IOExceptione){

              e.printStackTrace();thrownew RuntimeException(e);           

         }

     }   

     /**

      * 将文件的内容全部读取到一个byte数组中

      * 注意:仅适合小文件读取操作!

      * 参数是一个文件,返回值是一个数组对象

      * 1 首先检测是否存在文件,如果没有文件就抛出异常

      * 2 按照文件的长度创建数组对象

      * 3 使用IO方法读取文件到数组

      * 4 关闭文件

      */

     publicstatic byte[] saveBytes(String filename){

         try{

              Filefile = new File(filename);

              if(!file.exists()||!file.isFile()){

                   thrownew RuntimeException("不像个文件!");

              }

              if(file.length()>=Integer.MAX_VALUE){

                   thrownew RuntimeException("文件太大了");

              }

              byte[]buf= new byte[(int)file.length()];

              InputStreamin = new FileInputStream(file);

              in.read(buf);in.close();    return buf;

         }catch(IOExceptione){

              e.printStackTrace();thrownew RuntimeException(e);           

         }        

     }   

     //复制文件夹

     publicstatic void cpDir(File src,File dst){

         if(!src.isDirectory()){thrownew RuntimeException("src 必须是文件夹");}

         if(!dst.exists()){dst.mkdir();}

         File[]files=src.listFiles();

         if(files==null){return;}

         for(Filefile:files){

              if(file.isFile()){

                   cp(file,newFile(dst,file.getName()));

              }else{

                   cpDir(file,newFile(dst,file.getName()));

              }

         }

     }   

     publicstatic void cp(File src,File dst){

         try{

              RandomAccessFilein=new RandomAccessFile(src,"r");

              RandomAccessFileout = new RandomAccessFile(dst,"rw");

              intcount;

              byte[]buf= new byte[1024*512];

              while((count=in.read(buf))!=-1){out.write(buf,0,count);}

              in.close();out.close();             

         }catch(IOExceptione){

              e.printStackTrace();thrownew RuntimeException(e);

         }

     }   

     /**

      * 复制文件

      * @param src源文件

      * @param dst目标文件

      * 1 只读打开src

      * 2 读写方式打开dst

      * 3 从src读取一个byte

      * 4 向 dst写入一个byte

      * 5 读取结束,关闭文件

      */

     publicstatic void cp1(File src,File dst){

         try{

              RandomAccessFilein =new RandomAccessFile(src, "r");

              RandomAccessFileout =new RandomAccessFile(dst, "rw");

              //out输出,用于写出的文件

              intb;

              while((b=in.read())!=0xffffffff){//0xffffffff=-1

                   out.write(b);

              }

              in.close();out.close();

         }catch(IOExceptione){

              e.printStackTrace();thrownew RuntimeException(e);

         }

     }   

     //删除文件夹

     publicstatic boolean deletePath(File dir){

         File[]files= dir.listFiles();

         for(Filefile:files){

              if(file.isFile()){

                   if(file.delete()){

                       System.out.println("删除了:"+file);

                   }else{

                       System.out.println("木有删除!"+file);

                   }

              }else{

                   deletePath(file);

              }

         }

         returndir.delete();

     }   

     /**

      * 递归列目录

      * 1 列出当前文件夹内容(过滤根据扩展名过滤,如果递归就接受所有子文件夹)

      * 2 迭代显示文件夹内容

      *   如果是文件,就显示文件名

      *   如果是文件夹,缓存到线性列表中

      * 3 迭代缓存的文件夹

      *   递归显示每个文件夹的内容

      * @param dir 目录

      * @param exts 扩展名列表

      * @param r 是否递归

      */

     publicstatic void list(File dir,final String[] exts,final boolean r){

         File[]files= dir.listFiles(new FileFilter(){

              publicboolean accept(File file){

                   //如果是文件夹并且是递归列目录就接受这个文件夹

                   if(file.isDirectory()&& r){

                       returntrue;

                   }else{//如果是文件

                       for(Stringext:exts){

                            //迭代每个扩展名和文件名结尾比较

                            if(file.getName().endsWith(ext)){

                                 returntrue;//如果以扩展名为结尾,返回true

                            }

                       }

                   }

                   returnfalse;//迭代比较结束,都不成功返回false;

              }

         });       

     }   

     /**2迭代显示文件夹内容

      * 如果是文件,就显示文件明

      * 如果是文件夹,缓存到线性表中

        */

     publicstatic void list(File dir){

         File[]files=dir.listFiles();

         System.out.println("目录:"+dir.getAbsolutePath());

         if(files==null){

              return;

         }

         List<File>subs= new ArrayList<File>();

         for(Filefile:files){

              if(file.isFile()){

                   System.out.println(""+file.getName());

              }else{

                   subs.add(file);

              }

         }

         for(Filesub:subs){

              System.out.println("["+sub.getName()+"]");

         }

     }   

     /**

      * 将文件内容按照HEX打印到控制台

      * @param file

      */

    

     publicstatic void printHex(String file){

         try{

              RandomAccessFileraf= new RandomAccessFile(file,"r");

              intb;

              inti=1;

              while((b=raf.read())!=0xffffffff){

                   if(b<=0xf){

                       System.out.print("0");

                       }

                   System.out.print(Integer.toHexString(b)+"");

                   if(i++%16==0){

                       System.out.println();

                   }

              }

              raf.close();

         }catch(IOExceptione){

              e.printStackTrace();thrownew RuntimeException(e);

         }

     }   

     /**

      * 将byte[]数组按照16进制输出,没16byte为一行

      */

     publicstatic void printHex(byte[] ary){

         for(byteb:ary){

              intindex = 1;

              inti = b & 0xff;//高位消除,处理负数

              if(i<= 0xf){

                   System.out.print("0");                  

              }

              System.out.print(Integer.toHexString(i)+ " ");

              if(index++%16== 0){

                   System.out.println();

              }

         }        

     }

}

 

ISROSW.java

public class ISROSW {

     publicstatic void main(String[] args) throws Exception{

//        String str="我爱java";

//        FileOutputStream fos=newFileOutputStream("/home/tarena/abc.txt");

//        OutputStreamWriter osw=new OutputStreamWriter(fos,"GBK");

//        osw.write(str);osw.close();        

//        FileInputStream fis=newFileInputStream("/home/tarena/abc.txt");

//        InputStreamReader isr=newInputStreamReader(fis,"GBK");

//        char c=(char)isr.read();  charc2=(char)isr.read();

//        System.out.println(c);System.out.println(c2);       

         FileInputStreamfis=new FileInputStream("/home/tarena/abc.txt");

         InputStreamReaderisr=new InputStreamReader(fis,"GBK");

         BufferedReaderbr=new BufferedReader(isr);

         Stringstr=br.readLine();

         System.out.println(str);

         br.close();    

     }

}

 

PW.java

public class PW {

     publicstatic void main(String[] args) throws IOException{

         FileOutputStreamfos=new FileOutputStream("/home/tarena/55.txt");

         OutputStreamWriterosw=new OutputStreamWriter(fos,"GBK");

         PrintWriterpw=new PrintWriter(osw);

         pw.println("Hello");pw.println(newDate());pw.println(Math.random());pw.close();

     }

}

 

TestDISDOS.java

public class TestDISDOS {

//    public static void main(String[] args) throws IOException{

//        FileOutputStream fos=newFileOutputStream("/home/tarena/slf/sldfds");

//        DataOutputStream dos=new DataOutputStream(fos);

//        for(int i=0;i<100;i++){

//             doubleb=Math.random();System.out.println(b);dos.writeDouble(b);

//        }

//        dos.close();

//    }

     publicstatic void main(String[] args) throws IOException{

         FileInputStreamfis=new FileInputStream("/home/tarena/slf/sldfds");

         DataInputStreamdis=new DataInputStream(fis);

        

         for(inti=0;i<100;i++){

              Doubled=dis.readDouble();System.out.println(d);

         }

     }

}

RandomAccessFile

1 java.io 包

2 随即访问文件:可以在文件的任何位置读写

3 包含最基本的文件访问方法:intb=read() void write(int b)

4 包含基本类型的IO方法readInt writeInt() readDouble writeDouble()  readLongwriteLong() 等方法

 底层都是调用 read() write(int b) 实现的,

 读取方法在遇到文件末尾时抛出 EOFException(end of file =-1|0xffffffff) 作为结束标志

5 有字符串的IO处理方法,字符串写出需要编码!

 写出:先写出编码长度,然后写出 UTF-8 编码

 

double  写出的 byte 格式,是IEEE 754 标准 浮点数标准

 将 doule 数据序列化到文件中,再反序列化为double 值不变就可以

 

6 序列化:任何数据(基本类型,对象,图片,音乐)编码为 byte 序列的过程

 反序列化:将已经编码过的 byte 序列,重新解码为数据,叫反序列化

 

集合 io 多线程  网络  最重要的API

基本流

FileInputStream

FileOutputStream

 

处理流(提升)

     缓冲流 是InputStream/OutputStream的子类

     read write(读写一个字节)

     BufferedInputStream 连接的是 输入流read write flus

     BufferedOutputStream 连接的是 输出流

    

     数据输入/出流 是InputStream/OutputStream的子类

     DataInputStream  read(Int double long) write

     DataOutputStream

    

     读写文本  是Reader/Writer子类

     InputStreamReader  read一个字符 write一个字符串

     OutputStreamWriter 





0 0