第三次预习——java IO

该部分主要对应java2实用教程第十章的内容——输入、输出流(I/O)

预习内容还是翻阅书本,照着书上的代码,自己敲,然后运行,慢慢理解,这一部分可以接受它的概念,但不能很好的理解和运用。

IO流,即(Input/Output),主要用于设备间的输入与输出,
输入流:程序在运行期间,可能需要使用输入流从外部的存储媒介(硬盘等)或其他程序中读取所需要的数据。
输入流的指向称为它的
输出流:程序在处理数据后,可能需要使用输出流将处理的结果写入到永久的存储媒介中或传送给其他的应用程序。
输出流的指向称为它的目的地

File类

程序可能经常需要获取磁盘上文件的有关信息或在磁盘上创造新的文件等,这就需要学习使用File类。
File类的对象主要用来获取文件本身的一些信息,例如文件所在的目录、文件的长度或文件读写权限等,不涉及对文件的读写操作.
创建一个File对象的构造方法有3个:

  1. File(String filename);//文件的名字(默认与当前应用程序在同一目录中)
  2. File(String directoryPath,String filename);//文件的路径,文件的名字
  3. File(File dir,String filename);//文件的目录,文件的名字

文件的属性

public String getName()获取文件的名字
public String getAbsolute Path()获取文件的绝对路径
public String getParent()获取文件的父目录
public boolean canRead()判断文件是否可被读入
public boolean canWrite()判断文件是否可被写入
public boolean exists()判断文件是否存在
public boolean isFile()判断文件是否是一个普通文件,而不是目录
public boolean isDirectory()判断文件是否是一个目录
public long length()获取文件的长度
public long lastModified()获取文件最后修改的时间
于是,按照书上的例子,Example_10-1照着敲了一遍:

import java.io.*;
public class Example {
    public static void main(String args[]){

        File c = new File("C:\\Users\\lenovo\\Desktop","File.java");
        System.out.println(c.getName()+"是可读的吗:"+c.canRead());
        System.out.println(c.getName()+"的长度"+c.length());
        System.out.println(c.getName()+"的绝对路径"+c.getAbsolutePath());
        File file = new File("new.txt");
        System.out.println("在当前目录下创建新文件"+file.getName());
        if(!file.exists()){
            try{ file.createNewFile();
                System.out.println("创建成功");
            }
            catch(IOException exp){}
        }
    }
}

出现一下运行结果:
在这里插入图片描述
发现好像忘了建文件,于是建了
在这里插入图片描述
再次运行结果

在这里插入图片描述
但好像,new.txt没有创建成功,发现new.txt的目录没有写!!!
写上路径,再次运行,成功。
在这里插入图片描述
在这里插入图片描述

目录

  • 创建目录
    File对象调用方法public boolean mkdir()创建一个目录,创建成功返回true,否则返回false(该目录已经存在)。
  • 列出目录中的文件
    如果File对象是一个目录,那么对象调用下述方法列出该目录下的文件和子目录。
  1. public String[] list()字符串形式返回
  2. public File[] listFiles()File对象形式返回
    列出指定类型的文件:
  3. public String[] list(FilenameFilter 0bj)字符串返回指定类型
  4. public File[] listFiles(FilenameFilter obj)File对象返回指定类型
    上述两个方法的参数FilenameFilter是一个接口,该接口有一个方法:
public boolean accept(File dir,String name);

调用list方法时,需向该方法传递一个实现FilenameFilter接口的对象,
list方法执行时,参数obj不断回调接口方法accept(File dir,String name),该方法中的参数dir为调用list的当前目录dirFile,参数name被实例化dirFile目录中的一个文件名,当接口方法返回true时,list方法就将名字为name的文件存放到返回的数组中。//不太理解

import java.io.*;
public class Example {
   public static void main(String args[]) {
      File dirFile = new File("C:\Users\lenovo\Desktop");
      FileAccept fileAccept = new FileAccept();
      fileAccept.setExtendName("java");
      String fileName[] = dirFile.list(fileAccept);
      for(String name:fileName) {
          System.out.println(name);
      }
   }
}
class FileAccept implements FilenameFilter {
 private String extendName;
   public void setExtendName(String s) {
      extendName="."+s;
   }
   public boolean accept(File dir,String name) { //重写接口中的方法
      return name.endsWith(extendName);
   }
}

运行结果:运行结果貌似不对。。。尤其是"."这个到底???
在这里插入图片描述

文件的创建与删除

使用File类创建一个文件对象后,例如:

File file = new File ("C:\\myletter","letter.txt");

如果C:\myletter目录中没有名字letter.txt文件,文件对象file调用方法
public boolean createNewFile();

可以在C:\my letter目录中建立一个名字为letter.txt的文件。文件对象调用方法public boolean delect()可以删除当前文件,例如:

file.delect();

运行可执行文件

当要执行一个本地机器上的可执行文件时,可以使用java.lang包中的Runtime类。

Runtime ec;//使用Runtime类声明一个对象
ec = Runtime.getRuntime();//使用getRuntime()静态方法创建这个对象

ec可以调用exec(String command)方法打开本地机器上的可执行文件或执行一个操作。

import java.io.*;
public class Example {
   public static void main(String args[]) {
      try{ 
           Runtime ce=Runtime.getRuntime();
           File file=new File("c:/windows","Notepad.exe");
           ce.exec(file.getAbsolutePath());
           file=new File("C:\\Program Files\\Internet Explorer","IEXPLORE www.sohu.com ");
           ce.exec(file.getAbsolutePath());
      }
      catch(Exception e) {
         System.out.println(e);
      } 
   } 
}

运行结果:新浪网页+一个新的文件记事本
在这里插入图片描述

文件字节输入流

使用输入流的四个基本步骤:

  • 设定输入流的源
  • 创建指向源的输入流
  • 让输入流读取源中的数据
  • 关闭输入流

构造方法

使用FileInputSteam类的下列构造方法创建指向文件的输入流。

FileInputSteam(String name);
FileInputSteam(File file);

当出现I/O错误时,

try{
FileInputStream in = new FileInputStream("hello.txt");
}//在try块部分创建指向文件hello.txt的输入流
catch(IOException e){
System.out.printIn("File read error:"+e );
}//在catch(捕获)块部分检测并处理这个异常;

File f = new File("hello.txt");//指定输入流的源
try{
FileInputStream in = new FileInputStream(f);
}//创建指向源的输入流
catch(IOException e){
System.out.printIn("File read error:"+e );
};

使用输入流读取字节

  • in read()读取单个字节,返回字节值(0-255),未读出返回-1
  • in read(byte b[])读取b.length个字节到数组b中,返回实际读取的数目
  • int read(byte b[],int off,int len)参数off指定开始读取的位置,其他同上

关闭流

in.close();
上述举例:

import java.io.*;
public class Example{
   public static void main(String args[]) {
      int n=-1;
      byte [] a=new byte[100];
      try{  File f=new File("Example.java");
            InputStream in = new FileInputStream(f);
            while((n=in.read(a,0,100))!=-1) {
               String s=new String (a,0,n);
               System.out.print(s);
            }
            in.close();
      }
      catch(IOException e) {
           System.out.println("File read Error"+e);
      }
   }
}

运行结果:
在这里插入图片描述

文件字节输出流

使用输出流的四个基本步骤:(与输入流的类似)

  • 给出输出流的目的地
  • 创建指向目的地的输出流
  • 让输出流把数据写入到目的地
  • 关闭输出流

构造方法

使用FileOutputSteam类的下列构造方法创建指向文件的输出流。

FileOutputSteam(String name);
FileOutputSteam(File file);

当出现I/O错误时,

try{
FileOutputStream out = new FileOutputStream("destin.txt");
}//在try块部分创建指向文件destin.txt的输入流
catch(IOException e){
System.out.printIn("File write error:"+e );
}//在catch(捕获)块部分检测并处理这个异常;

File f = new File("destin.txt");//指定输出流的目的地
try{
FileOutputStream out = new FileOutputStream(f);
}//创建指向目的地的输出流
catch(IOException e){
System.out.printIn("Filewrite:"+e );
};

使用输入流读取字节

  • void write(int n)向目的地写入单个字节
  • void write(byte b[])写入一个字节数组
  • void write(byte b[],int off,int len)off处取len个字节写到目的地
  • void close()关闭输出流

关闭流

out.close()
上述举例:

import java.io.*;
public class Example {
    public static void main(String args[]) {
        byte [] a = "新年快乐".getBytes();
        byte [] b = "Happy New Year".getBytes();
        File file = new File("C:\\Users\\lenovo\\Desktop","a.txt");                         //输出的目的地
        try{
            OutputStream out=new FileOutputStream(file);      //指向目的地的输出流
            System.out.println(file.getName()+"的大小:"+file.length()+"字节");//a.txt的大小:0字节
            out.write(a);                                    //向目的地写数据
            out.close();
            out=new FileOutputStream(file,true);             //准备向文件尾加内容
            System.out.println(file.getName()+"的大小:"+file.length()+"字节");///a.txt的大小:8字节
            out.write(b,0,b.length);
            System.out.println(file.getName()+"的大小:"+file.length()+"字节");///a.txt的大小:22字节
            out.close();
        }
        catch(IOException e) {
            System.out.println("Error "+e);
        }
    }
}

在这里插入图片描述
在这里插入图片描述
PS:为什么"新年快乐"是12个字节???
造成8、12;22、26;的不同结果

文件字符输入、输出流

与字节流相对的是 字符流
在这里插入图片描述
构造方法:

  • FileReader(String filename);FileReader(File filename);
  • FileWriter(String filename);FileWriter(File filename);
  • FileWriter(String filename, boolean append);
    FileWriter(File filename, boolean append);
    字符输入流和输出流的read和write方法使用字符数组读写数据(以字符为基本单位处理数据)
import java.io.*;
public class Example{
    public static void main(String args[]) {
        File sourceFile = new File("C:\\Users\\lenovo\\Desktop\\a.txt");//读取的文件
        File targetFile = new File("C:\\Users\\lenovo\\Desktop\\b.txt");//写入的文件
        char c[] = new char [19];//char型数组
        try{
            Writer out = new FileWriter(targetFile,true);//指向目的地的输入流
            Reader in = new FileReader(sourceFile);//指向源的输入流
            int n = -1;
            while((n=in.read(c))!=-1){
                out.write(c,0,n);
            }
            out.flush();
            out.close();
        }
        catch(IOException e) {
            System.out.println("Error"+e);
        }
    }
}

运行结果:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

缓冲流

在这里插入图片描述

import java.io.*;
import java.util.*;
public class Example {
   public static void main(String args[]) {
      File fRead = new File("english.txt");
      File fWrite = new File("englishCount.txt");
      try{  Writer out = new FileWriter(fWrite);
            BufferedWriter bufferWrite = new BufferedWriter(out);
            Reader in = new FileReader(fRead);
            BufferedReader bufferRead =new BufferedReader(in);
            String str = null;
            while((str=bufferRead.readLine())!=null) {
               StringTokenizer fenxi = new StringTokenizer(str);
               int count=fenxi.countTokens();
               str = str+" 句子中单词个数:"+count;
               bufferWrite.write(str);
               bufferWrite.newLine();
            } 
            bufferWrite.close(); 
            out.close();
            in = new FileReader(fWrite);
            bufferRead =new BufferedReader(in);
            String s=null;
            System.out.println(fWrite.getName()+"内容:");
            while((s=bufferRead.readLine())!=null) {
              System.out.println(s);
           }  
           bufferRead.close();
           in.close();
      }
      catch(IOException e) {
          System.out.println(e.toString());
      }
   }
}

在这里插入图片描述
在这里插入图片描述

随机流

RandomAccessFile类既不是InputStream类的子类,也不是OutputStream类的子类,它创建的流的指向既可以作为流的源,也可以作为流的目的地。(既可以读取数据,也可以流入数据)
构造方法:

  • RandomAccessFile(String name,String mode)
  • RandomAccessFile(File file,String mode)
import java.io.*;
public class Example {
   public static void main(String args[]) {
      RandomAccessFile inAndOut=null;
      int data[]={1,2,3,4,5,6,7,8,9,10};
      try{ inAndOut=new RandomAccessFile("tom.dat","rw");
           for(int i=0;i<data.length;i++) {
              inAndOut.writeInt(data[i]);
           } 
           for(long i=data.length-1;i>=0;i--) { //一个int型数据占4个字节,inAndOut从
              inAndOut.seek(i*4);          //文件的第36个字节读取最后面的一个整数,
              System.out.printf("\t%d",inAndOut.readInt()); //每隔4个字节往前读取一个整数
           }
           inAndOut.close();
      }
      catch(IOException e){} 
   }
}

在这里插入图片描述

数组流

在这里插入图片描述

import java.io.*;
public class Example {
    public static void main(String args[]) {
        try{
            ByteArrayOutputStream outByte = new ByteArrayOutputStream();
            byte [] byteContent = "mid-autumn festival".getBytes();
            outByte.write(byteContent);
            ByteArrayInputStream inByte = new ByteArrayInputStream(outByte.toByteArray());
            byte backByte [] = new byte [outByte.toByteArray().length];
            inByte.read(backByte);
            System.out.println(new String(backByte));
            CharArrayWriter outChar = new CharArrayWriter();
            char [] charContent = "中秋快乐".toCharArray();
            outChar.write(charContent);
            CharArrayReader inChar = new CharArrayReader(outChar.toCharArray());
            char backChar [] = new char [outChar.toCharArray().length];
            inChar.read(backChar);
            System.out.println(new String(backChar));
        }
        catch(IOException exp){}
    }
}

在这里插入图片描述

数据流

在这里插入图片描述

import java.io.*;
public class Example {
    public static void main(String args[]) {
        File file = new File("apple.txt");
        try{	FileOutputStream fos = new FileOutputStream(file);
            DataOutputStream outData = new DataOutputStream(fos);
            outData.writeInt(100);
            outData.writeLong(123456);
            outData.writeFloat(3.1415926f);
            outData.writeDouble(987654321.1234);
            outData.writeBoolean(true);
            outData.writeChars("How are you doing");
        }
        catch(IOException exp){}
        try{ FileInputStream fis = new FileInputStream(file);
            DataInputStream inData = new DataInputStream(fis);
            System.out.println(inData.readInt());
            System.out.println(inData.readLong());
            System.out.println(inData.readFloat());
            System.out.println(inData.readDouble());
            System.out.println(inData.readBoolean());
            char c = '\0';
            while((c=inData.readChar())!='\0'){
                System.out.print(c);
            }
        }
        catch(IOException e){}
    }
}

在这里插入图片描述
字符串加密:

import java.io.*;
public class Example{
    public static void main(String args[]) {
        String command = "渡江总攻时间是4月22日晚10点 ";
        EncryptAndDecrypt person = new EncryptAndDecrypt();
        String password = "Tiger";
        String secret= person.encrypt (command, password);
        File file= new File("secret. txt") ;
        try{ FileOutputStream fos= new FileOutputStream(file);
            DataOutputStream outData = new DataOutputStream(fos);
            outData. writeUTF(secret);
            System.out.println("加密命令:"+secret) ;
        }
        catch (IOException e) {}
        try{ FileInputStream fis = new FileInputStream(file);
            DataInputStream inData = new DataInputStream(fis);
            String str = inData. readUTF();
            String mingwen = person.decrypt(str,password);
            System.out.println("解密命令:"+mingwen);
        }
        catch(IOException e){}
    }
}
 class EncryptAndDecrypt {
    String encrypt(String sourceString, String password){
        char[] p = password.toCharArray();
        int n = p.length;
        char[] c = sourceString.toCharArray();
        int m = c.length;
        for (int k = 0; k < m; k++) {
            int mima = c[k] + p[k % n];
            c[k] = (char)mima;
        }
        return new String(c);
    }

    String decrypt(String sourceString, String password) {
        char[] p = password.toCharArray();
        int n = p.length;
        char[] c = sourceString.toCharArray();
        int m = c.length;
        for (int k = 0; k < m; k++) {
            int mima = c[k] - p[k % n];
            c[k] = (char) mima;
        }
        return new String(c);
    }
}

在这里插入图片描述

对象流

在这里插入图片描述

import java.io.*;
class TV implements Serializable{
    String name;
    int price;
    public void setName(String s) {
        name=s;
    }
    public void setPrice(int n) {
        price=n;
    }
    public String getName() {
        return name;
    }
    public int getPrice() {
        return price;
    }
}


public class Example {
    public static void main(String args[]) {
        TV changhong = new TV();
        changhong.setName("长虹电视");
        changhong.setPrice(5678);
        File file=new File("television.txt");
        try{
            FileOutputStream fileOut=new FileOutputStream(file);
            ObjectOutputStream objectOut=new ObjectOutputStream(fileOut);
            objectOut.writeObject(changhong);
            objectOut.close();
            FileInputStream fileIn=new FileInputStream(file);
            ObjectInputStream objectIn=new ObjectInputStream(fileIn);
            TV xinfei=(TV)objectIn.readObject();
            objectIn.close();
            xinfei.setName("新飞电视");
            xinfei.setPrice(6666);
            System.out.println("changhong的名字:"+changhong.getName());
            System.out.println("changhong的价格:"+changhong.getPrice());
            System.out.println("xinfei的名字:"+xinfei.getName());
            System.out.println("xinfei的价格:"+xinfei.getPrice());
        }
        catch(ClassNotFoundException event) {
            System.out.println("不能读出对象");
        }
        catch(IOException event) {
            System.out.println(event);
        }
    }
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值