Java之IO流

①  File 类

1.1  文件操作

1、    创建目录

2、    创建文件

3、    相对路径和绝对路径

4、    删除文件

5、    遍历文件

import java.io.File
 
public class DemoFile {
   public static void main(String[]args) throws IOException {
       
      // 创建目录
      File file = new File("D:\\IO\\File");\\相当于file.separator
      file.mkdirs();
      
      // 创建文件
      File file1 = new File("D:\\IO\\File\\aaa.txt");
      file1.createNewFile();
      
      // 删除文件
      file1.delete();---删除文件夹,文件夹必须为空
      
      // 相对路径—产生在工程包下面
      File file2 = new File("aaa.txt");
      file2.createNewFile();
      file2.delete();
      
      // 遍历文件
      File file3 = new File("D:\\IO\\File");
      String[] str = file3.list();
      System.out.println(Arrays.toString(str));
      
      //list()方法返回的是没完整路径的文件名 listFiles()方法返回有完整路径的文件名
      File[] file4 = file3.listFiles();
      for (File f : file4) {
         System.out.println(f.getName());
      }
   }
}

1.2  File的属性

//File的属性
public class DemoFile3 {
   public static void main(String[]args) {
 
      File file = newFile("D:\\IO\\File");
      String[] str = file.list();
      System.out.println(Arrays.toString(str));
 
      System.out.println("-----------------");
 
      File file1 = newFile("D:\\IO\\File\\input.txt");
      System.out.println(file1.length());           //长度
      System.out.println(file1.getAbsolutePath());  //绝对路径 
      System.out.println(file1.exists());           //文件是否存在  
      System.out.println(file1.isDirectory());      //是否是文件夹
      System.out.println(file1.isFile());           //是否是文件
      System.out.println(file1.getParent());        //获取父文件夹
   }
}

路径分隔符 :windows 下 “\”; (File.separator)


②   FileInputStream(字节输入流)

2.1  文件读取

public class DemoInput {
 
   public static void main(String[]args) throws IOException {
 
      File file = new File("D:\\IO\\File\\input.txt");
 
      InputStream input = new FileInputStream(file);
 
      //一次性把数据全部读取到bs数组中,返回读入的字节总数
      byte[] bs = new byte[1024];
 
      int total = input.read(bs);
 
      System.out.println(new String(bs, 0, total));
 
      // 流关闭
      input.close();
 
   }
}

③   FileOutPutStream(字节输出流)

3.1  文件写出

public class DemoOutput {
 
   public static void main(String[]args) throws IOException {
 
      File file = new File("D:\\IO\\File\\output.txt"); //(file,true)将不会覆写内容;实现拼接
      
      OutputStream output = new FileOutputStream(file);
 
      String str = "我勒个去!!!";
 
      byte[] bs = str.getBytes();
 
      output.write(bs);
 
      output.close();
 
   }
 
}

输出流如果指向的文件不存在,则会自动创建


④   FileReader (字符输入流)

4.1  文件读取

public class DemoFileReader {
 
   public static void main(String[]args) throws IOException {
 
      File file = new File("D:\\IO\\File\\input.txt");
 
      Reader reader = new FileReader(file);
 
      char[] cs = new char[1024];
 
      int total = reader.read(cs);
 
      System.out.println(newString(cs, 0, total));
 
      reader.close();
 
   }

字符流使用到了缓冲区


⑤   FileWriter (字符输出流)

5.1  文件写出

public class DemoFileWriter {
 
   public static void main(String[]args) throws IOException {
 
        FileWriter fw=new FileWriter("D:\\IO\\File\\output.txt",true);
 
        //从第二个开始 往后写3个
        fw.write(new char[]{'A','B','+','R','C','D','E'},2,3);
 
        fw.write("一个字符串");
 
        fw.close();
 
   }
 
}
 

字符流使用到了缓冲区

 

⑥   转换流

字符流---->字节流
public class DemoChange {
   public static void main(String[]args) throws IOException {
   
      //输出
      FileOutputStream fos=new FileOutputStream("D:\\IO\\File\\output.txt",true);
 
      OutputStreamWriter writer=new OutputStreamWriter(fos);
 
      writer.write("xxxxxxxxxxxxxxx");
 
      writer.close();
      fos.close();
     
   }
 
}
 
字节流---->字符流
 
   public static void main(String[]args) throws IOException {
      //输入
      FileInputStream fis=new FileInputStream("D:\\IO\\File\\input.txt");
 
      InputStreamReader reader=new InputStreamReader(fis);
 
      char[] cs=new char[1024*100];
 
      int total=reader.read(cs);
 
      System.out.println(new String(cs,0,total));
 
      reader.close();
      fis.close();
 
   }
 
}


⑦   高级流

7.1  PrintWriter /PrintStream (打印流)

1.读写更效率-----缓冲区

2.可以直接操作多种类型的数据

3.异常少

public class DemoPrintWriter {

    public static void main(String[]args) throws IOException {
      
      // 低级流后面加true能实现高级流的追加功能,直接在高级流后面加true,则表示刷新;
      FileWriter fw = new FileWriter("D:\\IO\\File\\output.txt", true);
      PrintWriter pw = new PrintWriter(fw);
 
      pw.println(true);
      pw.println("中");
      pw.println(123);
      pw.println("A");
 
      pw.flush();// 刷新清空缓冲区
      pw.close();// 关闭流时会自动刷新一次缓冲区
   }
}

 

 

 

7.2  BufferReader(缓冲流)

public static void main(String[] args) throws IOException {
      FileReader fr=new FileReader("E:/test.txt");
      BufferedReader br=new BufferedReader(fr);
      String temp=null;
      while(true){
         temp=br.readLine();      //一次读一行
         if(temp==null){
            break;
         }
         System.out.println(temp);
        
      }
 
      br.close();
     
   }
}
 
 
 
public class DemoBuffer {
   public static void main(String[]args) throws IOException {
      FileReader fr=new FileReader("D:\\IO\\File\\buffer.txt");
      BufferedReader reader=new BufferedReader(fr);
      //从7开始复读
      int temp=0;
      int num=0;
      while(true){
         temp=reader.read();
         if((char)temp=='6')
            reader.mark(3);    //在某个位置打标记
        
         if((char)temp=='k'){
            if(num<3){
                reader.reset();    //返回刚才标记的地方
                num++;
            }
         }
           
         if(temp==-1){
            break;
         }
         System.out.print((char)temp);
      }
   }
}
 
 
 
public class Demo3{
   public static void main(String[] args) throwsIOException {
      FileWriter fw=new FileWriter("E:/bw.txt",true);
      BufferedWriter writer=new BufferedWriter(fw);
     
      writer.write("我是一些数据。。。");
      //换行
      writer.newLine();
     
      writer.flush();
      writer.close();
   }
 
 
               //关闭高级流时低级流也会关闭
 
 
 
    //当接收的类使用的是BufferedReader,发送的类是BufferedWriter的时候,要注意发送的一行要有换行标识符
 
    //PrintWriter中的println自带换行符
 
 
 
//缓冲区读取(键盘输入数据的标准使用)
public static void main(String[]args) throws IOException {
    BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
         System.out.println("请输入:");
         String str=reader.readLine();
         System.out.println(str);
     }
}


⑧  序列化和反序列化

1、实现Serializable接口

2、ObjectInputStream

3、ObjectOutputStream

注意  :

要想被序列化,必须实现Serializable标记接口

static 属性不会保存出去

一个普通属性不想被序列化出去:用transient修饰

对象序列化不可以追加

 

8.1  序列化(把对象保存到文件中)

File file = new File("D:\\IO\\XXX\\xxx.u");
List users= new ArrayList();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
    oos.writeObject(users);
    oos.close();


8.2  反序列化(把对象从文件中读取进来)

File file = new File("D:\\IO\\XXX\\xxx.u");
List users= newArrayList();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
    users =(List) ois.readObject();
     ois.close();

如何在类修改之后我们仍然能够反序列化

static final long serialVersionUID = 42L;

 

⑨   RandomAccessFile(随机读取流)

/*RandomAccessFile

 * 随机读取流  

 * 1.既能读,也能写

 * 2.能直接操作多种类型数据

 * 3.可以操作文件的任意位置

 * mode: 访问模式     r     rw

 */

public static void main1(String[] args) throws IOException{
    RandomAccessFile ran = new RandomAccessFile("D:\\IO\\File\\ran.txt", "rw");
      ran.write(65);
      ran.writeInt(65);
      ran.writeChar('A');
      ran.writeBoolean(true);
      ran.close();
   }
   
public static void main2(String[] args) throws IOException{
      File file = new File("D:\\IO\\File\\ran.txt");
      RandomAccessFile ran1 = new RandomAccessFile("D:\\IO\\File\\ran.txt", "rw");
      ran1.write(65);
      ran1.writeByte(66);
      ran1.write("DEFGRGTFGRFG".getBytes());
      // 跳到指定位置开始操作
      ran1.seek(5);
      // 跳过若干字节开始操作
      ran1.skipBytes((int) file.length());
      ran1.write("10086".getBytes());
      ran1.close();
 
   }
 

 

⑩   对象的克隆

 public class Cat implements Cloneable {//实现Cloneable接口  
 
    String name;
    int age;
 
    public Cat(String name, int age) {
       super();
       this.name= name;
       this.age= age;
    }
 
    @Override
    public String toString() {
       return"Cat [name=" + name + ", age=" + age + "]";
    }
 
    @Override
    protected Object clone() throws CloneNotSupportedException {
       // TODOAuto-generated method stub
       return super.clone();
    }
 
    public static void main(String[] args) throws CloneNotSupportedException{
       Cat c1= new Cat("小白", 22);
       Cat c2= (Cat) c1.clone();    //克隆后的对象开辟的是一个新的空间
       c2.name ="小黑";
       System.out.println(c1);
       System.out.println(c2);
    }
 
}
 
 
 
 

 

⑪   编码

UTF     UTF-8   UTF-16          世界编码        1-3字节
GBK     GB2312  GBK    GB18030  中国国标        2个字节
ISO8859-1                       西欧  不含中文  1个字节

ISO8859-1                       GBK
1000              ?     --->   中
1010              ?     --->   国
0001              ?     --->   字

public class DemoCode {
    public static void main(String[] args) throws IOException{
    RandomAccessFile ran = new RandomAccessFile("D:\\IO\\File\\input.txt", "r");
       String str = null;
       while((str = ran.readLine()) != null) {
           byte[] bs = str.getBytes("ISO8859-1");
           String str1 = new String(bs, "GBK");
           System.out.println(str1);
 
       }
 
       ran.close();
    }
 
}


⑫   枚举器

Enumeration<String> en = v.elements();

 

while(en.hasMoreElemebts()){

 

System.out.println(en.nextElement());

 

用于Vector的遍历


 

⑬   属性类

-----操作属性文件 (HashTable的子类键值对中放得都是字符串

 

public class Demo2 {
    public static void main1(String[] args) throws IOException{
    Properties   pro  =  new     Properties();
    pro.setProperty("size", "1000");
    OutputStream out=new FileOutputStream("D:\\pro.pro");
         pro.store(out, "hehe");//"hehe"为注释
         out.close();
     }
 
    public static void main2(String[] args)throws IOException {
        Properties   pro  =  new   Properties();
        InputStream input=new FileInputStream("D:\\pro.pro");
         pro.load(input);
         input.close();
         System.out.println(pro.getProperty("size"));
   }
   
}

 

 

⑭   文件的拷贝

public static void main(String[] args) throws IOException{
   // 方法1
   File file = new File("D:\\IO\\File\\win7.jpg");
   InputStream input = new FileInputStream(file);
   OutputStream output = new FileOutputStream("D:\\IO\\File\\win7\\win7.jpg", true);
   byte[] bs = new byte[1024];
   int total = 0;
   while ((total= input.read(bs)) != -1) {
      output.write(bs,0, total);
   }
 
   output.close();
   input.close();
   
 
 
 
   //方法2
   File file = new File("D:\\IO\\File\\DJ.mp3");
   FileInputStream input = new FileInputStream(file);
   FileOutputStream output = new FileOutputStream("D:\\IO\\File\\win7\\DJ.mp3");
   byte[] bs = new byte[1024];
   while (true) {
      int total = input.read(bs);//一次性读取1个byte字节数组大小的数据,返回值为int类型
      if (total == -1) {       
         break;                   
      }
      output.write(bs,0,total);
   }
   output.close();
   input.close();
   
}


文件的拷贝最好用字节流

纯文档的操作最好用字符流

 

 

⑮   文件的切割

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DemoCut {       //方法1
    public static void main(String[] args) throws IOException {
        FileInputStream input = new FileInputStream("D:\\IO\\File\\DJ.mp3");
        byte[] bs = new byte[1024* 1024];
        int total = 0;
        int num = 0;
        while (true) {
            total = input.read(bs);
            if (total == -1) {
                break;
            }
            FileOutputStream output = new FileOutputStream("D:\\IO\\File\\win7\\DJ" + num + ".mp3");
            num++;
            output.write(bs, 0, total);
            output.close();
        }
        input.close();
    }
}


public class DemoCut1 {         //方法2
    public static void main(String[]args) throws IOException {
        FileInputStream input = new FileInputStream("D:\\IO\\File\\DJ.mp3");
        byte[] bs = new byte[1024* 1024];
        for (int i = 0; i < 5; i++){
            FileOutputStream output = new FileOutputStream("D:\\IO\\File\\win7\\DJ" + i + ".mp3");
            int total = input.read(bs);
            output.write(bs, 0, total);
            output.close();
        }
        input.close();
    }
}
 
 


⑯   文件的合并

public class CombineDemo {
    public static void main(String[] args) throws IOException {
        FileOutputStream output = new FileOutputStream("D:\\IO\\File\\win7\\aaa.mp3");
        byte[] bs = new byte[1024* 1024];
        for (int i = 0; i < 5; i++){
            FileInputStream input = new FileInputStream("D:\\IO\\File\\win7\\DJ"+ i + ".mp3");
            int total = input.read(bs);
            output.write(bs, 0, total);
            input.close();
        }
        output.close();
    }
}

 

⑰   递归删除

public class DemoDelete {
    public static void main(String[]args) {
        delete(new File("D:\\IO\\File"));
    }

    public static void delete(File file) {
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()){
                delete(f);
            } else {
                f.delete();
            }
        }
        file.delete();
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值