Java初级--IO流(上)

来源:互联网 发布:下载一亩田软件 编辑:程序博客网 时间:2024/04/30 08:53

8.File类
     1)File类是IO包中唯一代表磁盘文件信息的类,而不是文件中的内容。
     2)File类定义了一些与平台无关的方法来操纵文件,例如,创建、删除文件和重命名文件。
     3)Java中的目录被当作一种特殊的文件使用,list方法可以返回目录中的所有子目录和文件名。
     4)在Unix下的路径分隔符/,在Dos 下的路径分隔符为\,Java 可以正确处理Unix 和Dos 的路径分隔符。

import java.io.*;import java.util.*;public class FileTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubFile f = new File("1.txt");if (f.exists()) {f.delete();System.out.println("******");} else {try {f.createNewFile();} catch (Exception e) {e.printStackTrace();}System.out.println("File name: " + f.getName());System.out.println("File path: " + f.getPath());System.out.println("File abs path: " + f.getAbsolutePath());System.out.println("File Parent: " + f.getParent());System.out.println(f.exists() ? "exist" : "not exist");System.out.println(f.canRead() ? "read" : "not read");System.out.println(f.isDirectory() ? "directory" : "not directory");System.out.println(f.canWrite() ? "write" : "not write");System.out.println("File last modified:" + new Date(f.lastModified()));}}}



9.RandomAccessFile 类
      1)提供了众多的文件访问方法;
      2)支持随机访问方式;
      3)在随机(相对顺序而言)读写等长记录格式的文件时有很大的优势。
      4)仅限于操作文件,不能访问其它的IO设备,如网络、内存影像等。
      5)两种构造方法
              new RandomAccessFile(f,“rw”);//读写方式
              new RandomAccessFile(f,"r")//只读方式

import java.io.*;class Employee {public String name;public int age;public static final int LEN = 8;public Employee(String name, int age) {if (name.length() > LEN) {name = name.substring(0, LEN);} else {while (name.length() < LEN) {name += "\u0000";}}this.name = name;this.age = age;}}public class RandomFileTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubEmployee e1 = new Employee("小白", 23);Employee e2 = new Employee("XB", 24);Employee e3 = new Employee("xiaobai", 25);try {RandomAccessFile ra = new RandomAccessFile("employee", "rw");ra.writeChars(e1.name);ra.writeInt(e1.age);ra.writeChars(e2.name);ra.writeInt(e2.age);ra.writeChars(e3.name);ra.writeInt(e3.age);ra.close();// int len = 0;// byte [] buf = new byte[Employee.LEN];String strName = "";RandomAccessFile raf = new RandomAccessFile("employee", "r");raf.skipBytes(Employee.LEN * 2 + 4);// len = raf.read(buf);// strName = new String(buf,0,len);for (int i = 0; i < Employee.LEN; i++) {strName += raf.readChar();}System.out.println(strName.trim() + ":" + raf.readInt());raf.seek(0);// len = raf.read(buf);// strName = new String(buf,0,len);strName = "";for (int i = 0; i < Employee.LEN; i++) {strName += raf.readChar();}System.out.println(strName.trim() + ":" + raf.readInt());raf.skipBytes(Employee.LEN * 2 + 4);// len = raf.read(buf);// strName = new String(buf,0,len);strName = "";for (int i = 0; i < Employee.LEN; i++) {strName += raf.readChar();}System.out.println(strName.trim() + ":" + raf.readInt());raf.close();} catch (Exception e) {e.printStackTrace();}}}


 

10.各种字节流类
      1)流是字节序列的抽象概念,文件是数据的静态存储形式,而流是指数据传输时的形态。流类分为两个大类:节点流类和过滤流类(也叫处理流类)
      2)InputStream 与 OutputStream 类
          InputStream 类:
                程序可以从中连续读取字节的对象叫输入流,在Java 中,用InputStream 类来描述所有输入流的抽象概念。
                InputStream 类的方法
                        int read() 从输入流中读取一个字节的内容,并把字节的内容以整数的形式返回,如果碰到流的结束就返回-1,如果没有碰到流的结束并且没有内容可读,就会发生堵塞。
                        int read(byte []b)
                        int read(byte []b,int off, int len)
                        int skip(long n)
                        int available()
                        void mark(int readlimit)
                        void reset()
                        boolean markSupported()
                        void close()

         有了垃圾回收器,为什么还要调用close方法?
         流是操作系统产生的资源,垃圾回收器不会管理系统产生的资源,需要自己调用close()方法来管理系统资源。
   

         OutputStream 类:
         程序可以向其中连续写入字节的对象叫输出流,在Java 中,用OutputStream 类来描述所有输出流的抽象类。

          OutputStream 类的方法:
                   void write(int b)
                   void write(byte []b)
                   void write(byte []b,int off,int len )
                   void flush()
                   void close()
   
       3)FileInputStream 与 FileOutputStream 类
          a)分别用来创建磁盘文件的输入流和输出流对象,通过它们的构造函数来指定文件路径和文件名。
          b)创建FileInputStream 实例对象时,指定的文件应当是存在和可读的,创建FileOutputStream 实例对象时,如果指定的文件已经存在,这个文件中的原来内容将被覆盖。
          c)对于一个磁盘文件创建创建FileInputStream 对象的两种方式。
                (I)FileInputStream inOne = new FileInputStream("hello.txt);
                (II)File f = new File("hello.txt");
                     FileInputStream inTwo = new FileInputStream(f);
           d)创建FileOutputStream 实例对象时,可以指定还不存在的文件名看,不能指定一个已经被其它程序打开了文件。

 

     4)Reader 与 Writer 类
            a)Reader和Writer 是所有字符流类的抽象基类,用于简化对字符串的输入输出编程,即用于读写文本数据。
            b)二进制文件和文本文件的区别
                  在不考虑正负数的情况下,每个字节中的数据可以是0~255之间的任意值,他们在内存中都是以二进制的形式存储,通常所说的文件,就是内存中的一片数据复制到硬盘上的存储形式,文件中的每个字节数据 也都是二进制形式的,文件系统中的每个文件都是二进制文件,各种文本字符是由一个或多个字节组成的, 其中每个字节的数据不能是任意的,它不能像二进制一样,从0~255之间都可以,而这些要表示字符的字节只能是0~255之间的一些特殊的数字,其它数字是都不可能出现的。如果一个文件中每个字节,或几个相邻的字节表示成某种字符,就可以称为文本文件,可见文本文件是二进制文件的一种特殊形式,为了与文本文件相区别,把文本文件外的其它文件称为二进制文件,简单认为, 如果一个文件专用于存储文本字符, 而没有包含字符之外的其它字符,称之为文本文件,除此之外的文件成为二进制文件。  
            c)Reader 和Writer 这两个类主要用于读写文本格式的内容。而InputStream 和OutputStream 用于读写二进制格式的内容。
  
     5)PipedInputStream 与 PipedOutputStream 类
         PipedInputStream 类与PipedOutputStream 类用于在应用程序中的创建管道通信。使用管道流类,可以实现各个程序模块之间的松耦合通信。

import java.io.PipedInputStream;import java.io.PipedOutputStream;class Sender extends Thread {private PipedOutputStream out = new PipedOutputStream();public PipedOutputStream getOutputStream() {return out;}public void run() {String strInfo = new String("hello,receiver!");try {out.write(strInfo.getBytes());out.close();} catch (Exception e) {e.printStackTrace();}}}class Receiver extends Thread {private PipedInputStream in = new PipedInputStream();public PipedInputStream getInputStream() {return in;}public void run() {byte[] buf = new byte[1024];int len = 0;try {len = in.read(buf);System.out.println("the following message comes frome sender:\n"+ new String(buf, 0, len));} catch (Exception e) {e.printStackTrace();}}}public class PipedStringTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubSender t1 = new Sender();Receiver t2 = new Receiver();PipedOutputStream out = t1.getOutputStream();PipedInputStream in = t2.getInputStream();try {out.connect(in);} catch (Exception e) {e.printStackTrace();}t1.start();t2.start();}}

 

     6)ByteArrayInputStream 与ByteArrayOutputStream类
        用于以IO流的方式来完成对字节数组内容的读写,来支持类似内存虚拟文件或者内存映像文件的功能。
        重视IO程序代码的复用:
        System.in 连接到键盘,是InputStream 类型的对象的实例对象。System.out连接到显示器,是PrimStream 类的对象实例;不管各种底层物理设备用什么方式实现数据的终止点,InputStream 的read 方法总是返回-1 来表示输入流的结束。在Windows 下,按下Ctrl+z 组合键可以产生键盘输入流的结束标记,在linux 下,则是按下Ctrl +D 组合键来产生键盘输入流的结束标记。

        建议:要编程从键盘上连续读取一大段数据时,应尽量将读取数据的过程放在函数中完成,使用-1 来作为键盘输入的节点,在该函数中编写的程序代码不应直接使用System.in 读取数据,而是用一个InputStream 类型的形式参数对象来读取数据,然后将System.in 作为实参传递给InputStream 类型的形式参数来调用该函数。

import java.io.*;public class ByteArrayTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubString tmp = "abcdefghijklmnopqrstuvwxyz";byte[] src = tmp.getBytes();ByteArrayInputStream input = new ByteArrayInputStream(src);ByteArrayOutputStream output = new ByteArrayOutputStream();transform(input, output);byte[] result = output.toByteArray();System.out.println(new String(result));transform(System.in, System.out);}public static void transform(InputStream in, OutputStream out) {int ch = 0;try {while ((ch = in.read()) != -1) {int upperCh = (int) Character.toUpperCase((char) ch);out.write(upperCh);}} catch (Exception e) {e.printStackTrace();}}}