Java基础 输入输出流

笔者由于身体不适,这次就草草的整理了一下

第九章 输入输出流

9.1 文件

  • File(String filename)
  • File(String directoryPath , String filename)
  • File(File f, string filename)
    • filename:文件名
    • directoryPath:文件路径
    • f:目录

9.1.1 文件的属性

  • public String getName()
  • public boolean canRead()
  • public boolean canWrite()
  • public boolean exist()
  • public long length()
  • public String getAbsolutePath()
  • public getParent()
  • public boolean isFile()
  • public boolean isDirectory()
  • public boolean isHidden()
  • public long lastModified()

9.1.2 目录

  • 创建目录
    • public boolean mkdir()
  • 列出目录中的文件
    • public String[] list()
    • public File[] listFile()
    • public String[] list(FilenameFliter obj)
    • public File[] listFile(FilenameFliter obj)
      • FilenameFliter是一个接口
      • 有一个方法是public boolean accept(File dir , String name)
      • 接口回调机制

9.1.3 文件的创建与删除

  • public boolean creatNewFile()
    • File f = new File(“C:\myletter”,”letter.txt”);
    • f.createNewFile()
    • f.delete()

9.1.4 运行可执行文件

  • RunTime ec = RunTime.getRunTime()
  • ec.exec(String command)

9.2 文件字节流

9.2.1 FileInputStream类

  • 该类的所有方法都是从inputStream中继承来的
  • 称为文件字节输入流
  • 构造函数的参数称为输入流的源
    • FileInputStream(String name)
    • FileInputStream(File file)
  • 异常类
    • IOException
  • 从输入流中读取数据
    • read方法
      • int read()
        • 从输入流中顺序读取单个字节的数据,返回0~255,读到末尾则返回-1
      • 将多个字节读到一个字节数组中
        • int read(byte [])
        • int read(byte [] , int off, int length)
          • byte[] 表示读取后存储的地方
          • int off表示偏移单位
          • int length指定读取的最大字节数
          • 返回的数字是实际读取的字节数字,读到末尾则返回-1

9.2.2 FileOutputStream类

  • 从outputStream的子类
  • 称为文件输出字节流
  • 构造方法的参数称为输出流的目的
    • FileOutputStream(String name)
    • FileOutputStream(File file)
  • 不存在还创建
  • 存在会刷新(默认),即重写
    • 可选择
      • FileOutputStream(File file , boolean append)
      • FileOutputStream(String name , boolean append)
        • true <==>不刷新
    • 用write()方法把数据写入输出流到达目的
      • public void write(byte[])
        • 把b.length个字节数据写入到输出流
      • public void write(byte[] , int off , int length)
        • 从给定字节数组中起始位置偏移off个位子写入length个字节到输出流
    • 只要不关闭流,每次调用write()就顺序写入到输出流中,直至流被关闭

Example3.java

package example3;
import java.io.*;
public class Example3 {
    public static void main(String args[]) {
        File file = new File("hello.txt");
        byte [] b = "欢迎,welcom".getBytes();
        try {
            FileOutputStream out = new FileOutputStream(file);
            out.write(b);
            out.close();
            FileInputStream in = new FileInputStream(file);
            int n = 0;
            do {
                n = in.read(b , 0 , 2);
                String str = new String(b,0,n);
                System.out.println(str);
            }
            while(n != -1);
        }
        catch(IOException e) {
            System.out.println(e);
        }
    }
}

9.3 文件字符流

9.3.1 FileReader类

  • 是Reader的子类
  • 其余几乎和FileInputStream一样
    • 构造方法
    • read()方法
      • 只不过把byte[ ] 换成 char[ ]

9.3.2 FileWriter类

  • 是Writer的子类
  • 其余几乎和FileOutputStream一样
    • 构造方法
    • write()方法
      • 只不过把byte[ ] 换成 char[ ]
      • 也有新的参数
        • public void writer(String str)
        • public void writer(String str , int off , int length)

Example4.java

package example4;
import java.io.*;
public class Example4 {
    public static void main(String args[]) {
        File file = new File("hello.txt");
        char b[] =  "欢迎 welcome".toCharArray();
        try {
            FileWriter writer = new FileWriter(file);
            writer.write(b);
            writer.write("欢迎来到北京");
            writer.close();
            FileReader r = new FileReader(file);
            int n = 0;
            do {
                n = r.read(b , 0 , 2);
                String str = new String(b,0,2);
                System.out.println(str);
            }
            while(n != -1);
        }
        catch(IOException e) {
            System.out.println(e);
        }
    }
}

Remark
* 对于Writer流,write方法将数据首先写入到缓冲区中,每当缓冲区溢出是,缓冲区的内容被自动写入到目的地,如果关闭流,换抽取的内容会被立刻写入到目的地。流调用flush()可以立刻冲洗当前缓冲区,即将当前缓冲区中的内容写入目的

9.4 缓冲流

可以读行

Example5.java

package example5;
import java.io.*;
public class Example5 {
    public static void main(String args[]) {
        File readFile = new File("Student.txt");
        File writeFile = new File("Hello.txt");
        try {
            FileReader inOne = new FileReader(readFile);
            BufferedReader inTwo = new BufferedReader(inOne);
            FileWriter tofile = new FileWriter(writeFile);
            BufferedWriter out =  new BufferedWriter(tofile);
            String s = null;
            int i = 0;
            do {
                s = inTwo.readLine();
                i++;
                out.write(i + " " + s);
                out.newLine();
            }
            while(s != null);
            out.flush();
            out.close();
            tofile.close();
            inOne = new FileReader(writeFile);
            inTwo = new BufferedReader(inOne);
            do {
                s = inTwo.readLine();
                System.out.println(s);
            }
            while(s != null);
            inOne.close();
            inTwo.close();
        }
        catch(IOException e) {
            System.out.println(e);
        }
    }
}

Example6.java

package example6;
import java.io.*;
import java.util.*;
public class Example6 {
    public static void main(String args[]) {
        Scanner inputAnswer = new Scanner(System.in);
        int score = 0;
        StringBuffer answer = new StringBuffer();
        String result = "ACDD";
        try {
            FileReader inOne = new FileReader("test.txt");
            BufferedReader inTwo = new BufferedReader(inOne);
            String s = null;
            do {
                s = inTwo.readLine();
                if(s == null) {
                    break;
                }
                if(!s.startsWith("*"))
                    System.out.println(s);
                if(s.startsWith("*")) {
                    System.out.println("输入选择的答案(A,B,C,D):");
                    String str = inputAnswer.nextLine();
                    try {
                        char c = str.charAt(0);
                        answer.append(c);
                    }
                    catch(StringIndexOutOfBoundsException exp) {
                        answer.append("*");
                    }
                }
            }
            while(s != null);
            inOne.close();
            inTwo.close();
        }
        catch(IOException exp) {}
        for(int i = 0 ; i < result.length() ; i++) {
            if(result.charAt(i) == answer.charAt(i) || result.charAt(i) == answer.charAt(i)
 - 32) {
        score ++;       
            }
        }
        System.out.printf("最后得分:%d\n",score);
    }
}

9.5 数据流

读取和写入指定数据类型的数据

Example7.java

package example7;
import java.io.*;
public class Example7 {
    public static void main(String args[]) {
        try {
            FileOutputStream fos = new FileOutputStream("jerry.txt");
            DataOutputStream out_data = new DataOutputStream(fos);
            out_data.writeInt(100);
            out_data.writeLong(123456);
            out_data.writeFloat(3.1415926f);
            out_data.writeBoolean(true);
            out_data.writeBoolean(false);
            out_data.writeChars("I am OK");
            out_data.close();
            fos.close();
        }
        catch(IOException e) {}
        try {
            FileInputStream fis = new FileInputStream("jerry.txt");
            DataInputStream in_data = new DataInputStream(fis);
            System.out.println(":" + in_data.readInt());
            System.out.println(":" + in_data.readLong());
            System.out.println(":" + in_data.readFloat());
            System.out.println(":" + in_data.readBoolean());
            System.out.println(":" + in_data.readBoolean());
            char c = '\0';
            do {
                c = in_data.readChar();
                System.out.print(c);
            }
            while(c != '\0') ;
            in_data.close();
            fis.close();
        }
        catch(IOException e) {}
    }
}

9.6 对象流

对象流进行读写操作
顺序的
* 自定义类要实现Serializable接口
* implements接口就行,不用具体实现接口的方法

TV.java

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

```

Example8.java

    package example8;
    import java.io.*;
    public class Example8 {
        public static void main(String args[]) {
            TV changhong = new TV();
            changhong.setName("changhong");
            changhong.setPrice(5678);
            File file =  new File("television.txt");
            try {
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream objectOut = new ObjectOutputStream(fos);
                objectOut.writeObject(changhong);
                objectOut.close();
                TV xinfei =  new TV();
                xinfei.setName("xinfei");
                xinfei.setPrice(6666);
                System.out.println(changhong.getName() + "的价格:" + changhong.getPrice()); 
                System.out.println(xinfei.getName() + "的价格:" + xinfei.getPrice());
            }
            /*
            catch(ClassNotFoundException e) {
                System.out.println("不能读出对象");
            }
            */
            catch(IOException e) {
                System.out.println(e);
            }
        }
    }

9.7 随机读写流

可以定位
* 构造方法
* RandomAccessFile(String name ,String mode)
* RandomAccessFile(File file , String mode)

  • seek(long pos)方法
  • getFilePointer()方法获得所在位置,字节数,返回long

Example9.java

package example9;
import java.io.*;
public class Example9 {
    public static void main(String args[]) {
        RandomAccessFile inAndOut = null;
        int data[] = {20,30,40,50,60};
        try {
            inAndOut = new RandomAccessFile("a.dat","rw");
            try {
                for(int i = 0 ; i < data.length ; i++)
                    inAndOut.writeInt(data[i]);
                for(long i = data.length - 1 ; i>=0 ;i--) {
                    inAndOut.seek(4*i);
                    System.out.printf("\t%d", inAndOut.readInt());
                }
            }
            catch(IOException e) {}
        }
        catch(Exception e) {}

    }
}

9.8 使用Scanner解析文件

  • Scanner(File file)
  • 默认分隔标志符
  • 正则表达式分隔标志符
    • useDelimiter(String regex)方法

Example10.java

package example10;
import java.io.*;
import java.util.*;
public class Example10 {
    public static void main(String args[]) {
        File file = new File("cost.txt");
        Scanner sc = null;
        int sum = 0;
        try {
            sc = new Scanner(file);
            while(sc.hasNext()) {
                try {
                    int price = sc.nextInt();
                    sum += price;
                    System.out.println(price);
                }
                catch(InputMismatchException e) {
                    String t = sc.next();
                }
            }
            System.out.println("The total costs is " + sum + " dolars");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}

Example11.java

package example11;
import java.io.*;
import java.util.*;
public class Example11 {
    public static void main(String args[]) {
        File file = new File("communicate.txt");
        double sum = 0;
        Scanner sc = null;
        try {
            sc = new Scanner(file);
            String regex = "[^0123456789.]+";
            sc.useDelimiter(regex);
            while(sc.hasNext()) {
                double price = sc.nextDouble();
                System.out.println(price);
                sum += price;
            }
        }
        catch(Exception e){
            System.out.println(e);
        }
        System.out.println("the total cost is " + sum + "CNY");
    }
}

Example12.java

package example12;
import java.util.*;
import java.io.*;
public class Example12 {
    public static void main(String args[]) {
        File file = new File("english.txt");
        TestWord test = new TestWord();
        test.setFile(file);
        test.setStopTime(5);
        test.startTest();
    }
}
class TestWord{
    File file;
    int stopTime;
    public void setFile(File file) {
        this.file = file;
    }
    public void setStopTime(int stopTime) {
        this.stopTime = stopTime;
    }
    public void startTest() {
        Scanner sc = null;
        Scanner read = new Scanner(System.in);
        int isRightNumber = 0;
        int wordNumber = 0;
        try {
            sc = new Scanner(file);
            while(sc.hasNext()) {
                wordNumber++;
                String word = sc.next();
                System.out.printf("给%d秒的时间背单词%s\n", stopTime,word);
                Thread.sleep(stopTime * 1000);
                System.out.printf("\r");        //将光标移动到本行开头
                for(int i = 0 ; i < 50 ; i++) {
                    System.out.print("*");
                }
                System.out.printf("\n请输入显示的单词:");
                String input = read.nextLine();
                if(input == null) {
                    input = "****";
                }
                if(input.equals(word)) {
                    isRightNumber++;
                }
                System.out.printf("当前正确率:%5.2f \n", 100*(float)isRightNumber / wordNumber);
            }
            System.out.printf("正确率:%5.2f \n", 100*(float)isRightNumber / wordNumber);
        }
        catch(Exception exp) {
            System.out.println(exp);
            System.out.println(exp.getMessage());
            exp.printStackTrace();
        }
    }
}

9.9 小结

  1. 输入流的指向称作源,程序从指向源的输入流中读取源中的数据;输出流的指向称作目的地,程序通过向输出流中写入数据把信息传递到目的地
  2. InputStream的子类创建的对象称作字节输入流。字节输入流按字节读取源中的数据,只要不关闭流,每次调用读取方法就顺序地读取源中的其余内容
  3. Reader类创建的子类称为字符输入流,按字符读取数据,其余几乎同上
  4. OutputStream的子类的对象称作字节输出流。将数据写入指向输出流指向的目的中
  5. Writer的子类的对象称作字符出书流,按照字符,其余几乎同上

以上内容均根据《Java基础教程(第三版)》整理而成

你可能感兴趣的:(Java基础)