简谈 FileInputStream 和 FileOutputStream 的使用方法

    技术2022-05-11  78

     

        对文件的读写操作一直是我的薄弱环节,这都是错误的学习习惯导致的:每门课程我都是开始时学得蛮认真的,所以基础相对比较扎实一点;但是到后来就越学越放松,所以后面的一块就变得模模糊糊的,而Java 课程中的I/O 也是放在靠后的位置来介绍的,所以这一块学得不咋的。。。

        今天上午又在看《 Ivor Horton’s Beginning Java 2, JDK 5 Edition 》(《Java 2 入门经典》),写了几个例题。

     

    首先看看API中是怎么描述FileInputStream的:

      public   class  FileInputStreamextends InputStreamFileInputStream 从文件系统中的某个文件中获取输入字节。哪些文件可用取决于主机环境。    FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。  

      

    FileInputStream(File file) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。 FileInputStream(FileDescriptor fdObj):通过使用文件描述符 fdObj 创建一个 FileInputStream,该文件描述符表示到文件系统中某个实际文件的现有连接。 FileInputStream(String name):通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。

     

     

    下面这个例题是使用通道将字符串写入文件的

       

    package  com.bulaoge.alenc; import  java.io.File; import  java.io.FileOutputStream; import  java.io.IOException; import  java.io.FileNotFoundException; import  java.nio.ByteBuffer; import  java.nio.channels.FileChannel;  /** * @title WriteAString.java * @author Alenc */   public   class  WriteAString  {       public static void main(String[] args) {                            String phrase = new String("Garbage in, Garbage out ");              String dirname = "C:/";              String filename = "out.txt";                            File dir = new File(dirname);              //check out the directory              if(!dir.exists()){                     if(!dir.mkdir()){                            System.out.println("Cannot creat directory: " + dirname);                            System.exit(1);                     }              } else if(!dir.isDirectory()) {                     System.out.println(dirname + " is not a director");                     System.exit(1);              }                            //creat the filestream              File aFile = new File(dir, filename);              FileOutputStream outputFile = null;              try {                     outputFile = new FileOutputStream(aFile);                     System.out.println("File stream created successfully.");              } catch(FileNotFoundException e) {                     e.printStackTrace(System.err);              }                            //creat the file output stream channel and the buffer              FileChannel outChannel = outputFile.getChannel();              ByteBuffer buf = ByteBuffer.allocate(1024);              System.out.println("New buffer:                 position = " + buf.position() +                                                  " Limit = " + buf.limit() + " capacity = " +                                                 buf.capacity());              //            /**//            * This code can be only compile under JDK1.5//            *///            for(char ch : phrase.toCharArray()) {//                   buf.putChar(ch);//            }              char[] ch = phrase.toCharArray();              for(int j=0; j<ch.length; j++{                     buf.putChar(ch[j]);              }              System.out.println("Buffer after loading: postion = " + buf.position()                                                 + " Limit = " + buf.limit() + " capacity = "                                                 + buf.capacity());              buf.flip();              System.out.println("Buffer after flip: position = " + buf.position()                                                 + " Limit = " + buf.limit() + " capacity = "                                                 + buf.capacity());                            //write the file              try{                     outChannel.write(buf);                     outputFile.close();                     System.out.println("Buffer contents written to file.");              } catch(IOException e) {                     e.printStackTrace(System.err);              }              System.exit(0);       }}

     

     

    编译后运行程序会得到如下的结果:

       

    C:study > java  - ea  - cp . WriteAStringFile stream created successfully.New buffer:             position  =   0     Limit  =   1024     capacity  =   1024 Buffer after loading: postion  =   116      Limit  =   1024     capacity  =   1024 Buffer after flip: position  =   0  Limit  =   116      capacity  =   1024 Buffer contents written to file.

     

     

    此时,在目录 C:/ 会有一个文本文件 out.txt ,就是该程序写到磁盘上的

    out.txt 文件中包含如下文字:

     

     

    G a r b a g e   i n ,   G a r b a g e   o u t .   I t s   j u s t   a   t e s t   o f   m y   f a v o r   J a v a

     

    显示的字符之间出现空格,是因为输出的是8位的字符,而写入文件的时Unicode字符码。对于Unicode 字符码来说,字符串每个字符占用两个字节。

     

     

     

    下面再看看API中是怎么描述FileReadStream的:

     

    构造方法有:

            public   class  FileOutputStreamextends OutputStream文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流。文件是否可用或能否可以被创建取决于基础平台。特别是某些平台一次只允许一个 FileOutputStream(或其他文件写入对象)打开文件进行写入。在这种情况下,如果所涉及的文件已经打开,则此类中的构造方法将失败。 FileOutputStream 用于写入诸如图像数据之类的原始字节的流。要写入字符流,请考虑使用 FileWriter。

     

     

     

    FileOutputStream(File file):创建一个向指定 File 对象表示的文件中写入数据的文件输出流。 FileOutputStream(File file,  boolean  append) :创建一个向指定 File 对象表示的文件中写入数据的文件输出流。 FileOutputStream(FileDescriptor fdObj) :创建一个向指定文件描述符处写入数据的输出文件流,该文件描述符表示一个到文件系统中的某个实际文件的现有连接。 FileOutputStream(String name) :创建一个向具有指定名称的文件中写入数据的输出文件流。 FileOutputStream(String name,  boolean  append) :创建一个向具有指定 name 的文件中写入数据的输出文件流。

     

     

     

     

    下面再写一个读取刚刚创建的 out.txt文件的程序:

     

     

    编译后运行程序会得到如下的结果:

     

    C:study > javac  - classpath . ReadAString.java C:study > java  - enableassertions  - classpath . ReadAStringFile contains  116  bytes.String read: Garbage in, Garbage out.String read:  Its just a test of my fString read: avor Java EOF reached.
    构造方法有:

    最新回复(0)