文件和I/O流

版权声明:本文为[博主](https://zhangkn.github.io)原创文章,未经博主同意不得转载。https://creativecommons.org/licenses/by-nc-sa/2.5/cn/ https://blog.csdn.net/u011018979/article/details/24844661

前言

1.File的用于创建文件夹、用于表示文件夹、用于创建文件、用于表示文件和用于删除文件或文件夹。

2.字符流:abstract class Reader和Writer操作的是文本文件

3.缓冲字符流(BufferedReader和BufferedWriter)每次读取或写入一行

缓冲流(BufferedInputStream和BufferedOutputStream)每次读取或写入一个数组的大小。

4.打印字符流属于处理流。不能和介质直接相连

 5.装饰器模式:动态的给对象添加职责,提供了一个比继承更好地弹性方案。

正文

文件java.io.File

An abstract representation of file and directory pathnames,仅仅用于表示文件文件夹的信息(文件、类型和扩展名),不能对文件内容进行訪问。当中\仅仅适用于windows,而/路径分隔符适用unix和window。

1.API

1)File(String pathname)
          Creates a new File instance by converting the given pathname string into an abstract pathname

2) long length()
          Returns the length of the file denoted by this abstract pathname.获取文件的大小,假设文件内容为空或者文件不存在就返回零。

3) String getName()
          Returns the name of the file or directory denoted by this abstract pathname.

4) long lastModified()
          Returns the time that the file denoted by this abstract pathname was last modified.

5) String getPath()
          Converts this abstract pathname into a pathname string.获取全路径名

6) boolean exists()
          Tests whether the file or directory denoted by this abstract pathname exists.

7)boolean isFile()
          Tests whether the file denoted by this abstract pathname is a normal file.

8) boolean isDirectory()
          Tests whether the file denoted by this abstract pathname is a directory.

9) boolean createNewFile()
          Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

10)boolean mkdir()
          Creates the directory named by this abstract pathname. 仅仅能创建最后一级文件夹。
 boolean mkdirs()
          Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. 用于创建一个完整的文件夹树。

11) boolean delete()
          Deletes the file or directory denoted by this abstract pathname仅仅能删除文件或空文件夹。


 File getParentFile()
          Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory. File getParentFile()
 1))案例:删除文件:

public class deleFileDemo{
    
    public static void main(String[] argts){
        File dir1=new Flie("D:\soft软件\快逸设计器EXE");
        for(;;){
            if(dir1==null){
                break;
            }
            dir1.delete();
            dir1=dir1.getParentFile();
        }
    }
}

12) String[] list()
          Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
 String[] list(FilenameFilter filter)
          Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
 File[] listFiles()
          Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
 File[] listFiles(FileFilter filter)
          Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
 File[] listFiles(FilenameFilter filter)
          Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
补充:FileFilter和FilenameFilter

1))FileFilter

A filter for abstract pathnames

boolean accept(File pathname)
          Tests whether or not the specified abstract pathname should be included in a pathname list.

2))FilenameFilter

boolean accept(File dir, String name)
          Tests if a specified file should be included in a file list.

3))案例:搜索文件

public class listFilesDemo{
    public static void main(String[] args){
        File dir =new File("C:\FavoriteVideo");
        File[] file=dir.listFiles(new FileFilter(){
            public boolean accept(File pathname){
                String fileName=pathname.getName();
                return  fileName.endsWith(".exe");
            }
                
            
        })
    }
}
注:上述代码使用了回调模式。

FileFilter由dir创建,它却调用了创建者dir的资源(pahtName).
 
13)) int available()
          Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
返回此输入流下一个方法调用能够不受堵塞地从此输入流读取(或跳过)的预计字节数。
 

RandomAccessFile

Instances of this class support both reading and writing to a random access file.

在文件内部使用一个指针来任意指向文件的不论什么位置。通过该指针訪问文件内容。

指针会随着读写操作自己主动后移。

1.API:

1)RandomAccessFile(File file, String mode)
          Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. String mode:r代表读,w代表写,rw代表读写。

 

2) int read()
          Reads a byte of data from this file由于读取的是文件内容的一字节。所以把它无符号扩展为int.

 void write(int b)
          Writes the specified byte to this file.仅仅把int数值的低8位作为数据存储。

3) long getFilePointer()
          Returns the current offset in this file.

4) void seek(long pos)
          Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

5) long length()
          Returns the length of this file.

6) void close()
          Closes this random access file stream and releases any system resources associated with the stream

顺序读取(I/O流)

读取的文件类型有二进制文件和文本文件。

I/O流的类型:字节流(InputStream和OutputStream);字节流(reader和writer)

1.抽象类:InputStream和OutputStream 字节流的根类。

1)InputStream

This abstract class is the superclass of all classes representing an input stream of bytes.

abstract  int read()
          Reads the next byte of data from the input stream.从流中读取饿一个字节,返回值为int类型。

读取的数据占低8位,高24位为0(进行无符号扩展)。

2)OutputStream

abstract  void write(int b)
          Writes the specified byte to this output stream.把一个字节写入到流中(把int的低8位写入流中)

2.文件流(FileInputStream和FileOutputStream)

文件流是节点流,能够直接操作磁盘文件

注:类的结构

1)Class FileInputStream
java.lang.Object
  java.io.InputStream
      java.io.FileInputStream

2)Class FileOutputStream
java.lang.Object
  java.io.OutputStream
java.io.FileOutputStream

 

3.缓冲流(BufferedInputStream和BufferedOutputStream)

缓冲流。一边和程序连接。一边和修士刘或接电流连接。

修士刘不能直接面对外部介质(文件和网络)

注:类的结构

 1)Class BufferedInputStream
java.lang.Object
  java.io.InputStream
      java.io.FilterInputStream
          java.io.BufferedInputStream
2)Class BufferedOutputStream
java.lang.Object
  java.io.OutputStream
      java.io.FilterOutputStream
          java.io.BufferedOutputStream

 

 

4.案例1:读取文件

public class readDemo{
    public static void main(String[] args){
        //建立程序与文件之间的管道
        InputStream fis=new FileInputStream("c:/a.txt");
        while(fis.available()!=0){//每次读取文件内容而返回的,此输入流下一个方法调用能够不受堵塞地从此输入流读取(或跳过)的预计字节数。假设达到文件末尾返回零。  Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
            int i=fis.read();
            System.out.println((char)(i&0xFF));//获取i的第八位
        }
        //关闭文件
        fis.close();//关闭当前正在操作的文件,否则其它程序无法使用该文件。Closes this file input stream and releases any system resources associated with the stream
    }
}

案例2:缓冲流读取文件内容

public class BufferedInputStreamDemo{
    public static void main(String[] args){
        //构建缓冲流new BufferedInputStreamDemo(InputStream is)
        BufferedInputStream bis=new BufferedInputStreamDemo(new FileInputStream("c:/a.txt"));
        //读取文件内容使用从FilterInputStream继承的方法: int read(byte[] b)           Reads up to byte.length bytes of data from this input stream into an array of bytes.
        //Returns:the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. 
        byte[] b=new byte[1024*8];
        int i=0;
        while((i=bis.read(b))!=-1){
            System.out.println(new String(b,o,i));//偏移量i为
        }
        //关闭管道
        bis.close();
    }
}

 

注:FilterInputStream

Class FilterInputStream
java.lang.Object
  java.io.InputStream
      java.io.FilterInputStream

1)API

 int read(byte[] b)
          Reads up to byte.length bytes of data from this input stream into an array of bytes.

Returns:the total number of bytes read into the buffer, or-1 if there is no more data because the end of the stream has been reached.

 

 

字符流:abstract class Reader和Writer

 

操作的是文本文件.

reader is a Abstract class for reading character streams;Writer is a Abstract class for writing to character streams.

1.Reader

1)类结构

Direct Known Subclasses:
BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader

2)API

 int read()
          Reads a single character读取的文本文件内容为每次读取一个字符(char),,将char字符进行无符号扩展为32位;使用低16位存储字符数据。

2.Writer

1)类结构

Direct Known Subclasses:
BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
2)API

 void write(int c)
          Writes a single character 将整形的低16位以字符的形式写入到文件里。

 

注:字符集

1)ASCII:表示键盘的键位

2)GBK/GBK2312(大陆):中文os默认gbk

3)utf-8:适用于网络传输。

英文使用1个字节,拉丁文使用2个字节,中文和日文使用3个字节

4)ISO8859-1:欧洲通用标准

5)unicode:使用两个字节表示世界上文字。

转换流

将字节流转换成字符流的流(InputStreamReader和OutputStreamWriter)。

1.InputStreamReader

1)类结构

 

Class InputStreamReader
java.lang.Object
  java.io.Reader
      java.io.InputStreamReader

Direct Known Subclasses:
FileReader

 

2)API

1))InputStreamReader(InputStream in, Charset cs)
          Creates an InputStreamReader that uses the given charset

2))public int read(char[] cbuf)
         throws IOExceptionReads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

Parameters:
cbuf - Destination buffer
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

这是从Reader继承的方法。

2.OutputStreamWriter

1)类结构

Class OutputStreamWriter
java.lang.Object
  java.io.Writer
      java.io.OutputStreamWriter

2)API

1))OutputStreamWriter(OutputStream out, Charset cs)
          Creates an OutputStreamWriter that uses the given charset

2))public void write(char[] cbuf)
Writes an array of characters.

3)) void flush()
          Flushes the stream

注:关闭管道之前将缓冲区的数据涮出

 

文件字符流(FileReader和FileWriter)

1.FileReader1)类结构

Class FileReader
java.lang.Object
  java.io.Reader
      java.io.InputStreamReader
          java.io.FileReader

2)API

FileReader(String fileName)
Creates a new FileReader, given the name of the file to read from.

2.FileWriter

1)类结构

 


Class FileWriter
java.lang.Object
  java.io.Writer
      java.io.OutputStreamWriter
          java.io.FileWriter

 

 

2)API

FileWriter(String fileName)
Constructs a FileWriter object given a file name

 注:文件字符流与转换流的差别

文件字符流仅仅能使用当前的操作系统的字符集,转换流相对灵活。

缓冲字符流(BufferedReader和BufferedWriter)

1.

1)类结构

Class BufferedReader
java.lang.Object
       java.io.Reader
            java.io.BufferedReader

2)API

String readLine()
Reads a line of text.

Returns:A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

 

注:通常能够配合String的split方法来分解行的信息

3)案例:下载

import  java.net.URL;//Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web
/**
从文件、控制台和网络读取内容。仅仅是读取的数据来源(截止)不同而已。
*/
public class URLDemo{
    public static void main(String[] args){
        //URL(String spec)  Creates a URL object from the String representation.
        URL url=new URL("http://zhangmenshiting.baidu.com/data2/music/1008960/100895568400128.mp3?xcode=bc377b0ac51a49f97331244f9f558ee65ed2cbb2fde1fdc6");
        //URLConnection openConnection() Returns a URLConnection instance that represents a connection to the remote object referred to by the URL. 
        //InputStream getInputStream() Returns an input stream that reads from this open connection 
        InputStream ips=url.openConnection().getInputStream();
        //写到文件里即完毕下载
    }
}

 

2.BufferedWriter

1)类结构

Class BufferedWriter
java.lang.Object
         java.io.Writer
             java.io.BufferedWriter

2)API

 

 

打印字符流(PrintWriter)

 

 

1)类结构


Class PrintWriter
 
java.lang.Object
 java.io.Writer
 java.io.PrintWriter
 
2)API

1))void write(String s)
Writes a string.

2))PrintWriter append(char c)
Appends the specified character to this writer

3))void println(String x)
Prints a String and then terminates the line

系列化和反序列化(ObjectInputStream和ObjectOutputStream)

 

将内存中的对象转换成byte流的过程叫系列化;将byte流转换成内存中的对象的过程叫反序列化。

1.ObjectInputStream

For example to read from a stream as written by the example in ObjectOutputStream:

      FileInputStream fis = new FileInputStream("t.tmp");
      ObjectInputStream ois = new ObjectInputStream(fis);

      int i = ois.readInt();
      String today = (String) ois.readObject();
      Date date = (Date) ois.readObject();

      ois.close();

1)类结构

 


Class ObjectInputStream
 
java.lang.Object
 java.io.InputStream
 java.io.ObjectInputStream
 

 

 
2)API

 Object readObject()
Read an object from the ObjectInputStream.从介质中读取对象,假设达到文件末尾直接抛出EOFException。

注:

1.參与系列化的对象必须实现Serializable接口。Serializable接口是空接口,起到一个标识作用。

2.transient:

被该keyword修饰的属性不參与系列化。一般修饰保密的字段。

 

 

 

2.ObjectOutputStream

1)类结构

 


Class ObjectOutputStream
 
java.lang.Object
 java.io.OutputStream
 java.io.ObjectOutputStream
 

 
2)API

1)void writeObject(Object obj)
Write the specified object to the ObjectOutputStream.

2)void reset()
Reset will disregard the state of any objects already written to the stream.经常使用于继续系列化对象。

 

 注:深拷贝

 

 

装饰器设计模式(decorator)

分为装饰器decorator和被装饰着decorate。

装饰者能够在被托付的对象之前或之后把它的行为加上,来完毕剩下的任务。

1.原理:

装饰器为被装饰者提供装饰的原料。比方:在jdk的应用中的I/O流,节点流是装饰器。节点流获取的数据来填充(修饰)缓冲流中的缓冲池。

意图在执行时组合操作产生新的变化。

解释:

FilterInputStream拥有InputStream类型的引用。把InputStream作为成员的目的是为了和IInputStream类型的子类进行组合。

样例:FilterInputStream的子类BufferredInputStream就能够被InputStream的子类FileInputStream节点流装饰,FileInpuStream使用获取的数据来填充缓冲池。

达到装饰者能够在被托付的对象之前或之后。把它的行为加上,以便来完毕剩下的任务。

它的缺点是造成大量的小类。

代码演示样例:

package zx.decorator;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/**
*装饰者能够在被托付的对象之前或之后,把它的行为加上,以便完毕剩下的任务。

当然。它的缺点是造成大量的小类 */ public class IOTest { public static void main(String[] args) throws Exception { FileWriter writer = new FileWriter("text.txt");//文件字符流是装饰器,将获取的数据来填充buff缓冲流中的缓冲池。文件里的数据来修饰缓冲池 BufferedWriter buff = new BufferedWriter(writer);//进行组合操作来产生新的功能 buff.write("haoren,250...."); buff.flush(); buff.close(); writer.close(); } }

 

 

2.装饰模式的特点

(1) 装饰对象和真实对象有同样的接口。这样client对象就能够和真实对象同样的方式和装饰对象交互。
 
(2) 装饰对象包括一个真实对象的引用(reference)
 
(3) 装饰对象接受全部来自client的请求。

它把这些请求转发给真实的对象。


 
(4) 装饰对象能够在转发这些请求曾经或以后添加一些附加功能。这样就确保了在执行时,不用改动给定对象的结构就能够在外部添加附加的功能。

在面向对象的设计中。一般是通过继承来实现对给定类的功能扩展。

 

3适用性

下面情况使用Decorator模式
 
1. 须要扩展一个类的功能,或给一个类加入附加职责。
 
2. 须要动态的给一个对象加入功能,这些功能能够再动态的撤销。
 
3. 须要添加由一些基本功能的排列组合而产生的非常大量的功能。从而使继承关系变的不现实。


 
4. 当不能採用生成子类的方法进行扩充时。一种情况是。可能有大量独立的扩展。为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。还有一种情况可能是由于类定义被隐藏,或类定义不能用于生成子类。

 

4长处

1. Decorator模式与继承关系的目的都是要扩展对象的功能。可是Decorator能够提供比继承很多其它的灵活性。
 
2. 通过使用不同的详细装饰类以及这些装饰类的排列组合,设计师能够创造出非常多不同行为的组合。

 

5缺点

1. 这样的比继承更加灵活机动的特性。也同一时候意味着更加多的复杂性。
 
2. 装饰模式会导致设计中出现很多小类,假设过度使用,会使程序变得非常复杂。


 
3. 装饰模式是针对抽象组件(Component)类型编程。

可是。假设你要针对详细组件编程时,就应该又一次思考你的应用架构,以及装饰者是否合适。

当然也能够改变Component接口,添加新的公开的行为,实现“半透明”的装饰者模式。在实际项目中要做出最佳选择。

 

6设计原则

1. 多用组合。少用继承。


 
利用继承设计子类的行为,是在编译时静态决定的。并且全部的子类都会继承到同样的行为。

然而。假设能够利用组合的做法扩展对象的行为,就能够在执行时动态地进行扩展。
 
2. 类应设计的对扩展开放,对改动关闭。

 


7装饰者与适配者模式的差别编辑

1.关于新职责:适配器也能够在转换时添加新的职责,但主要目的不在此。装饰者模式主要是给被装饰者添加新职责的。


 
2.关于原接口:适配器模式是用新接口来调用原接口,原接口对新系统是不可见或者说不可用的。装饰者模式原封不动的使用原接口。系统对装饰的对象也通过原接口来完毕使用。(添加新接口的装饰者模式能够觉得是其变种--“半透明”装饰者)
 
3.关于其包裹的对象:适配器是知道被适配者的详细情况的(就是那个类或那个接口)。装饰者仅仅知道其接口是什么。至于其详细类型(是基类还是其它派生类)仅仅有在执行期间才知道。

 

MVC软件设计思想(controller、view和module)

控制器:负责将用户请求发送到界面或模型 .Action

视图:界面(控制台、swing、web浏览器和手机UI).View

模型:与客观世界相相应的一种数据模型。BIZ和DAO

 

 

总结

訪问二进制

 

1.new BufferedInputStream(new FileInputStream(String name)) ;

2.new BufferedOutStream(new FileOutStream(String name)) ;

訪问文本文件

 

1.new InputStreamReader(new FileInputStream(String name),Charset cs)

2.new OutputStreamWriter(new FileOutStream(String name),Charset cs)

3.new FileReader(String fileName) 。不转换字符集情况下读取文本文件
4.new FileWriter(String fileName)不转换字符集情况下写文本文件

 

从控制台按行读取数据

 

1.new BufferedReader(new InputStreamReader(System.in)) ;

从文件按行读取数据

 

1.new BufferedReader(new InputStreamReader(new FileInputStream()),Charset cs) ;

 2.new BufferedReader(new FileReader(String fileName)) 。

 

将各种类型的数据以字符串的形式输出

 

 

1.new PrintWriter(new OutStreamReader(new FileOutStream()),Charset cs) ;

2.new PrintWriter(new FileWriter(String fileName)) ;

节点流和处理流

 

节点流:FileOutStream,FileInputStream

处理流:

BufferedReader/BufferedWriter/BufferedInputStream /BufferedOutStream /OutputStreamWriter 和OutputStreamReader

即是节点流也是处理流:

FileReader/FileWriter/PrintWriter

 

posted on 2019-04-15 14:07  xfgnongmin  阅读(200)  评论(0编辑  收藏  举报

导航