黑马程序员-IO(一)

来源:互联网 发布:php修改ad用户源代码 编辑:程序博客网 时间:2024/05/16 05:44

------- android培训、java培训、期待与您交流! ----------

1.      File类

a)        File类是IO包中唯一代表磁盘文件本身信息的类,而不是文件中的内容

b)       File类定义了一些与平台无关的方法来操纵文件,例如,创建、删除文件和重用名文件。

c)       Java中的目录被当做一种特殊的文件使用,list方法可以返回目录中的所有子目录和文件名

d)       在Unix下的路径分隔符为(/),在dos下的路径分隔符为(\),java可以正确处理Unix和Dos的路径分隔符。

编程举例:判断某个文件是否存在,存在则删除,不存在则创建。

例:

public class FileTest {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

       // TODO Auto-generatedmethod stub

       File f = new File("1.txt");

       if(f.exists()){

           f.delete();

           System.out.println("delete");

       }else {

           try {

              f.createNewFile();

           } catch (IOException e) {

              // TODO Auto-generatedcatch block

              e.printStackTrace();

           }

       }

       System.out.println("Filename:" + f.getName());

       System.out.println("Filepath:" + f.getPath());

       System.out.println("File abspath:" + f.getAbsolutePath());

       System.out.println("FileParent:" + 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("File lastmodified:" +new Date(f.lastModified()));

 

    }

 

}

2.      RandomAccessFile类

a)        提供了众多的文件访问方法

b)       支持随机访问方式

c)       在随机(相对顺序而言)读写等长度记录格式的文件时有很大的优势

d)       仅限于操作文件,不能访问其他IO设备,如网络,内存映像等

e)        两种构造方法:

                                      i.             new RandomAccessFile(f,”rw”);//读写方式

                                    ii.             new RandomAccessFile(f,”r”);//只读方式

编程实例:往文件中写入三名员工的信息,每个员工含有姓名和年龄两个字段,然后按照第二名、第一名、第三名的先后顺序读出员工信息。

员工类:

public class Employee {

    public Stringname =null;

    public int age = 0;

    public static final int LEN = 8;//规定字符数

   

    public Employee(String name,int age) {

       if(name.length() >LEN){

           //当名字字符大于字符数时,截掉后面的

           this.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)throws Exception{

       // TODO Auto-generatedmethod stub

       Employee e1 = new Employee("张三", 258);

       Employee e2 = new Employee("李四", 28);

       Employee e3 = new Employee("王五", 65);

      

       RandomAccessFile ra = new RandomAccessFile("employee.txt","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 = newbyte[Employee.LEN];

       String strName = "";

       RandomAccessFile raf = new RandomAccessFile("employee.txt","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());

       strName = "";

      

       raf.seek(0);

       //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());

       strName = "";

      

       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.close();

    }

 

}

3.      节点流

a)        理解流的概念

                                      i.             流是字节序列的抽象概念

                                    ii.             文件时数据的静态存储形式,而流是指数据传输时的形态

                                   iii.             流类分为两个大类:节点流类和过滤流类(也叫出力流类)

b)InputStream类

       程序可以从连续读取字节的对象叫输入流,在java中,用InputStream类来描述所有输入流的抽象概念。

c)     InputStream类的方法:

                                                    i.             int read()  二进制形式为11111111的数据,以byte类型表示为-1,以int类型表示为255

                                                  ii.             int read(byte[] b)

                                                 iii.             int read(byte b,int off,intlen)

                                                iv.             long skip(long n)

                                                  v.             int available()

                                                vi.             void mark(int readlimit)

                                               vii.             void reset()

                                             viii.             boolean markSupported()

                                                ix.             void close()

d)OutputStream类

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

e)      OutputStream类的方法:

                                                    i.             void write(int b)

                                                  ii.             void write(byte[] b)

                                                 iii.             void write(byte[] b,int off,intlen)

                                                iv.             void flush()

                                                  v.             void closs()


4.    FileInputStream与FileOutputStream类

                                                    i.             FileInputStream与FileOutputStream类分别用来创建磁盘文件的输入流和输出流对象,通过它们的构造函数来指定文件路径和文件名。

                                                  ii.             创建FileInputStream实例对象时,指定的文件应是存在和可读的。创建FileOutputStream实例对象时,如果指定的文件已经存在,这个文件中的原来内容将被覆盖清除。

                                                 iii.             对同一个磁盘文件创建FileInputStream对象的两种方式

a)        FileInputStream inOne = newFileInputStream(“hello.test”);

b)       File f = new File(“hello.test”);

FileInputStreaminTwo = new FileInputStream(f);

                                                iv.             创建FileOutputStream实例对象时,可以指定还不存在的文件名,不能指定一个已被其他程序打开了的文件。

                    

编程举例:用FileOutputStream类向文件写入一个字符串,然后用FileInputStream读出写入的内容。

       public class FileStream {

 

    /**

     * @param args

     */

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

       // TODO Auto-generatedmethod stub

       File f  = new File("hello.txt");

       FileOutputStream out= new FileOutputStream(f);

           out.write("www.it315.org".getBytes());

           out.close();

 

 

      

       byte[] buf =newbyte[1024];

       FileInputStream in = new FileInputStream(f);

       int len = in.read(buf);

       System.out.println(new String(buf,0,len));

       in.close();

 

    }

 

}

 

5.    Reader与Writer类

                                                    i.             Reader和Writer是所有字符流类的抽象基类,用于简化对字符串的输入输出编程,即用于读写文本数据

                                                  ii.             二进制文件和文本文件的去别

文本文件:专门存放文本   二进制文件:存放非文本文件

public class FileStream2{

 

    /**

     * @param args

     */

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

       // TODO Auto-generatedmethod stub

       File f = new File("hello2.txt");

       FileWriter out = new FileWriter(f);

       out.write("www.baidu.com");

       out.close();

      

       char[] buf =newchar[1024];

       FileReader in = new FileReader(f);

       int len = in.read(buf);

       in.close();

       System.out.println(new String(buf,0,len));

      

 

    }

 

}

6.    PipedInputStream与PipedOutputStream类

用于在应用程序中的创建线程管道通信

使用管道流类,可以实现各个程序模块之间的松耦合通信

Sender:

public class Sender extends Thread {

    private PipedOutputStreamout =new PipedOutputStream();

    public PipedOutputStream getOutputStream(){

       returnout;

    }

    public void run(){

       String strInfo = new String("hello,receiver");

       try {

           out.write(strInfo.getBytes());

           out.close();

       } catch (IOException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

    }

}

Receiver:

public class Receiver extends Thread {

    private PipedInputStreamin =new PipedInputStream();

    public PipedInputStream getInputStream(){

       returnin;

    }

    public void run(){

       byte[] buf =newbyte[1024];

       try {

           int len =in.read(buf);

           System.out.println("thefollowing message comes from sender:\n" +

                  new String(buf,0,len));

           in.close();

       } catch (IOException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

    }

}

 

PipedStreamTest:

public class PipedStreamTest {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

       // TODO Auto-generatedmethod stub

       Sender t1 = new Sender();

       Receiver t2 = new Receiver();

      

       PipedOutputStream out = t1.getOutputStream();

       PipedInputStream in = t2.getInputStream();

       try {

           out.connect(in);

       } catch (IOException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

      

       t1.start();

       t2.start();

 

    }

 

}

7.    ByteArrayInputStream与ByteArrayOutputStream类

                                                    i.             ByteArrayInputStream与ByteArrayOutputStream,用于以IO流的方式来完成对字节数组内容的读写,来支持类似内存虚拟文件或者内存映像文件的功能。

                                                  ii.             ByteArrayInputStream的两个构造函数:

a)        ByteArrayInputStream(byte[]buf)

b)       ByteArrayInputStream(byte[]buf,int offset,int length)

                                                 iii.             ByteArrayOutputStream的两个构造函数:

a)        ByteArrayOutputStream()

b)       ByteArrayOutputStream(int)

                                                iv.             编程举例:编写一个把输入流中所有英文字母变成大写字母,然后将结果写入到一个输出流对象。用这个函数来将一个字符串的所有字符转换成大写。

public class ByteArrayTest {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

       // TODO Auto-generatedmethod stub

       String tmp = "abcdefghijklmnopqrstuvwxyz";

       byte[] src = tmp.getBytes();

       ByteArrayInputStream input = new ByteArrayInputStream(src);

       ByteArrayOutputStream output = new ByteArrayOutputStream();

       transform(input, output);

       try {

           input.close();

           output.close();

       } catch (IOException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

       byte[] result = output.toByteArray();

       System.out.println(new String(result));

      

      

}

}

8. 重视IO程序代码的复用

                                                    i.             System.in连接到键盘,是InputStream类型的实例对象。System.out连接到显示器,是PrintStream类的实例对象。

                                                  ii.             不管各种底层物理设备用什么方式实现数据的终止点,InputStream的read方法总是返回-1来表示输入流的结束。

                                                 iii.             在windows下,按下Ctrl+Z组合键可以产生键盘输入流的结束标记,在linux下,则是按下Ctrl+D组合键来产生键盘输入流的结束标记。

编程举例:借助上一页编写的喊声,将键盘上输入的内容转变为大写字母后打印在屏幕上。

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

 

加入如下方法:

       transform(System.in, System.out);

   

   

    public static void transform(InputStream in,OutputStream out){

       int ch = 0;

       try {

           while((ch = in.read()) != -1){

              int upperCh = Character.toUpperCase((char)ch);

              out.write(upperCh);

           }

       } catch (IOException e) {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

       }

    }

 

9. 字符编码

                                                    i.             计算机里只有数字,计算机软件里的一切都是用数字来表示的,屏幕上显示的一个个字符也不例外。

                                                  ii.             字符a对应数字97,字符b对应数字98等,这种字符与数字对应的编码规则被称为ASCII(美国标准信息交换码)。ASCII的最高bit位都为0,也就是说这些数字都在0到127之间。

                                                 iii.             中国大陆将每一个中文字符都用两个字节的数字来表示,中文字符的每个字节的最高位bit都为1,中国大陆为每个中文字符指定的编码规则称为GB2312(国标码)

                                                iv.             在GB2312的基础上,对更多的中文字符(包括繁体)进行编码,新的编码规则称为GBK

                                                  v.             在中国大陆使用的计算机系统上,GBK和GB2312就被称为该系统的本地字符集。

                                                vi.             “中国”的”中”字,在中国大陆的编码是十六进制的D6D0,而在中国台湾的编码是十六进制的A4A4,台湾地区对中文字符集的编码规则称为BIG5(大五码)

                                               vii.             在一个国家的本地化系统中出现的一个字符,通过电子邮箱传送到另一个国家的本地化系统中,看到的就不是那个原始字符了,而是另外那个国家一个字符或乱码。

Unicode

UTF-8

UTF-16

10. 过滤流和包装类

a)        包装类的概念与作用

Ø        通过FileOutputStream对象将一个浮点小数写入到文件中,你感觉有点困难吧?能否通过FileOutputStream对象之间将一个整数写入到文件呢?

Ø        假如有个DataOutputStream类提供了往各种输出流对象中写入各种类型的数据(当然包括浮点小数)的方法。你现在所要做的工作就是:传递一个FileOutputStream输出流对象给DataOutputStream实例对象和调用DataOutputStream实例对象的用于写入浮点小数的方法

Ø        DataOutputStream并没有对应到任何具体的流设备,一定要给他传递一个对应具体流设备的输出流对象,完成类似的DataOutputStream功能的类就是一个包装类,也叫做过滤流泪或处理流类。

Ø        DataOutputStream包装类的构造函数语法:

PublicDataOutputStream(OutputStream out)

Ø        DataOutputStream的部分方法列表:

1.        public final voidwriteBoolean(boolean v)

2.        public final voidwriteShort(int v)

3.        public final void writeChar(intv)

4.        public final void writeInt(intv)

5.        public final voidwriteLong(long v)

6.        public final voidwriteFloat(float v)

7.        public final voidwriteDouble(double v)

8.        public final voidwriteBytes(String s)


原创粉丝点击