Java I/O类库


       System.out.println(“Released Lock”);

2.  InputStream及相关装饰器

Java I/O类库 - 自由之声 - 天涯在线的博客

InputStream的作用是用来表示那些不同数据源发生的类。

功能

构造器参数

ByteArrayInputStream

View buffers have three important advantages over the families of type-specific get and put methods described above:

作为一种数据源:将其与FilterInputStream工具相连以提供有用接口。

StringBufferInputStream

用于从文件中读取信息

FileInputStream

String转化成InputStream

PipedInputStream

发生用于写入相关PipedOutput Stream的数据。实现“管讲化”概念

SequenceInputStream

       缓冲器容纳的是普通的字节,为了把它们转化成字符,我们要么在输入它们的时候对其进行编码,要么在将其从缓冲器输出时对它们进行解码。可以使用java.nio.charset.CharSet类实现这些功能,该类提供了把数据编码成多种不同类型的字符集的工具:


抽象类,作为“装饰器”的接口。此中,“装饰器”为其他的InputStream类提供有用功能。

 

FilterInputStream

功能

DataInputStream

DataOutputStream搭配使用,因此我们可以根据可移植方式从流读取根基数据类型(int, char, long等)

A byte buffer. s

使用它可以防止每次读取时都得进行实际写操纵,代表“使用缓冲区”

LineNumberInputStream

跟踪输入中的行号,可调用getLineNumber()setLineNumber(int)

&昵图网nbsp;



 float  getFloat(int index)



构造器参数




FilterInputStream

     PipedOutputStream


3.  OutputStream及相关装饰器

DataInputStream搭配使用,因此可以根据可移植方式向流中写入根基类型数据(int, char, long等)

  • Absolute and relative get and put methods that read and write single bytes;
  • Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;
  • Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;
  • Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;
  • Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and
  • Methods for compacting, duplicating, and slicing a byte buffer.

Byte buffers can be created either by allocation, which allocates space for the buffer's content, or by wrapping an existing byte array into a buffer.

功能


ByteArrayOutputStream

在内存中创建缓冲区。所有送往“流”的数据都要放置在此缓冲区。

 

OutputStream,该类别决定了输出所要去往的目标:字节数据,文件或管讲

用于将信息写至文件

PipedOutputStream

任何写入此中的信息都会自动作为相关PipedInputStream的输出。实现“管讲化”概念。

FilterOutputStream

抽象类,作为“装饰器”的接口。此中,“装饰器”为其他OutputStream提供有用功能。

 

FilterOutputStream

功能

DataOutputStream

Java I/O类库 - 自由之声 - 天涯在线的博客

PrintStream

用于发生格式化输出。此中DataOutputStream处理数据的存储,PrintStream处理显示

BufferedOutputStream

使用它以避免每次发送数据时都要进行实际的写操纵。代表“使用缓冲区”。可以调用flush()清空缓冲区。

      

    无相应的类

Java I/O类库 - 自由之声 - 天涯在线的博客Java I/O类库 - 自由之声 - 天涯在线的博客

FileOutputStream

有时我们必须把来自于“字节”层次结构中的类和“字符”层次结构中的类结合起来使用。为了实现这个目的,要用到“适配器”类:InputstreamReader可以把InputStream转换为Reader,而OutputStreamWriter可以把OutputStream转换为Writer

设计ReaderWriter继续层次结构主要是为了国际化。

来源与去处:Java 1.0

相应的Java 1.1

      InputStream

      Reader 适配器:InputStreamReader

     OutputStream

      Writer 适配器:OutputStreamWriter

FileInputStream

FileReader

FileOutputStream

FileWriter

     StringBufferInputStream

  (已弃用)

For access to homogeneous binary data, that is, sequences of values of the same type, this class defines methods that can create views of a given byte buffer. A view buffer is simply another buffer whose content is backed by the byte buffer. Changes to the byte buffer's content will be visible in the view buffer, and vice versa; the two buffers' position, limit, and mark values are independent. The asFloatBuffer method, for example, creates an instance of the FloatBuffer class that is backed by the byte buffer upon which the method is invoked. Corresponding view-creation methods are defined for the types char, short, int, long, and double.

ByteBuffer

 

      StringWriter

    ByteArrayInputStream

     CharArrayReader

    ByteArrayOutputStream

              System.out.println((char)out.get(i));

     PipedInputStream

}


PipedWriter

      StringReader

       无论我们何时使用readLine(),都不应该使用DataInputStream(这会遭到编译器的强烈反对),而应该使用BufferedReader。除了这一点,DataInputStream仍是I/O类库的首选成员。

       为了更容易地过渡到使用PrintWriter,它提供了一个既能接受Writer工具又能接受任何OutputStream工具的构造器。PrintWriter的格式化接口实际上与PrintStream相同。

5UTF8ASCII编码成单一字节的形式,而非ASCII字符则编码成两到三个字节的形式。另外,字符串的长度存储在UTF8字符串的前两个字节中。

例如:

ByteBuffer buff = ByteBuffer.allocate(BSIZE);

       标准I/O重定向:

       setIn(InputStream), setout(PrintStream), setErr(PrintStream)

 bb.putShort(3);

Import java.io.*;

 

Public class Redirecting {

Fos.close();

       PrintStream console = System.out;

       BufferedInputStream in = new BufferedInputStream(new FileInputStream(“Redirecting.java”);

A direct byte buffer may also be created by mapping a region of a file directly into memory. An implementation of the Java platform may optionally support the creation of direct byte buffers from native code via JNI. If an instance of one of these kinds of buffers refers to an inaccessible region of memory then an attempt to access that region will not change the buffer's content and will cause an unspecified exception to be thrown either at the time of the access or at some later time.

This class defines six categories of operations upon byte buffers:

       System.setOut(out);

       System.setErr(out);

       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

       String s;

       While((s = br.readLine()) != null)

              System.out.println(s);

       Out.close();

将两个或多个InputStream工具转换成单一InputStream

}

}

bb.rewind();

       由于Externalizable工具在默认情况下不保存他们的任何字段,所以transient关键字只能和Serializable工具一起使用。

4.  ReaderWriter

I/O类库中有三个类被修改了,用以发生FileChannel。这三个被修改的类是FileInputStream, FileOutputStream以及用于既读又写的RandomAccessFile.  实例只能发生一个独一的channel.

tryLock()是非阻塞式的,它设法获取锁,但是如果不能获得(当其他一些进程已经持有相同的锁,并且不同享时),它将直接从方法调用返回。Lock()则是阻塞式的,它要阻塞进程直至锁可以获得,或调用lock()的线程中断,或调用lock()的通讲关闭。使用FileLock.release()可以开释锁。

通讲是一种相当基础的东西:可以向它传送用于读写的ByteBuffer,并且可以锁定文件的某些区域用于独占式接见。

       更改流的行为:固然BufferedOutputStreamFilterOutputStream的子类,但是BufferedWriter并不是FilterWriter的子类(固然FilterWriter是抽象类,没有任何子类,把它放在那里也只是把它作为一个占位符,或仅仅让我们不会对它所在的地方发生疑惑)。

独一直接与通讲交互的缓冲器是ByteBuffer.

BufferedInputStream

       System.setIn(in);

 

Direct vs. non-direct buffers

 

A direct byte buffer may be created by invoking the allocateDirect factory method of this class. The buffers returned by this method typically have somewhat higher allocation and deallocation costs than non-direct buffers. The contents of direct buffers may reside outside of the normal garbage-collected heap, and so their impact upon the memory footprint of an application might not be obvious. It is therefore recommended that direct buffers be allocated primarily for large, long-lived buffers that are subject to the underlying system's native I/O operations. In general it is best to allocate direct buffers only when they yield a measureable gain in program performance.

       PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(“test.out”)));

Whether a byte buffer is direct or non-direct may be determined by invoking its isDirect method. This method is provided so that explicit buffer management can be done in performance-critical code.

Access to binary data

This class defines methods for reading and writing values of all other primitive types, except boolean. Primitive values are translated to (or from) sequences of bytes according to the buffer's current byte order, which may be retrieved and modified via the order methods. Specific byte orders are represented by instances of the ByteOrder class. The initial order of a byte buffer is always BIG_ENDIAN.

For access to heterogeneous binary data, that is, sequences of values of different types, this class defines a family of absolute and relative get and put methods for each type. For 32-bit floating-point values, for example, this class defines:

 float  getFloat()

bb.asCharBuffer().put(“abcdef”);

       在调用ObjectOutputStream.writeObject()时,会查抄所传递的Serializable工具,看看是否实现了它自己的writeObject(),如果是这样,就跳过正常的序列化过程并调用它的writeObject().readObject()的情形与此相同。

一旦调用缓冲器上相对的get()put()函数,position指针就会随之相应改变。我们也可以调用绝对的,包含一个索引参数的get()put()方法(参数指明get()put()的发生位置)。不过,这些方法不会改变缓冲器的position指针。

Corresponding methods are defined for the types char, short, int, long, and double. The index parameters of the absolute get and put methods are in terms of bytes rather than of the type being read or written.

PushbackInputStream

       Rewind: rewind this buffer. The position is set to zero and the mark is discarded.

  • A view buffer is indexed not in terms of bytes but rather in terms of the type-specific size of its values;
  • A view buffer provides relative bulk get and put methods that can transfer contiguous sequences of values between a buffer and an array or some other buffer of the same type; and
  • A view buffer is potentially much more efficient because it will be direct if, and only if, its backing byte buffer is direct.

The byte order of a view buffer is fixed to be that of its byte buffer at the time that the view is created.

Invocation chaining

Methods in this class that do not otherwise have a value to return are specified to return the buffer upon which they are invoked. This allows method invocations to be chained. The sequence of statements

 bb.putInt(0xCAFEBABE);

例:

 bb.putShort(45);

can, for example, be replaced by the single statement

 bb.putInt(0xCAFEBABE).putShort(3).putShort(45);

 

       将字节存放于ByteBuffer的方法之一是:使用一种“put”方法直接对他们进行填充,填入一个或多个字节,或根基数据类型的值。不过,也可以使用warp()方法将已存在的字节数组“包装”到ByteBuffer中。一旦如此,就不再复制底层的数组,而是把它作为所发生的ByteBuffer的存储器,我们称之为数组支持的ByteBuffer

       达到更高的速度也有可能,方法就是使用accocateDirect()而不是allocate(),以发生一个与操纵系统有更高耦合性的“直接”缓冲器。但是,这种分配的开支会更大,并且具体实现也随操纵系统的不同而不同,因此必须再次实际运转利用程序来查看直接缓冲器是否可以使我们获得速度上的优势。

 

8 转换数据

       System.setOut(console);

      

       根据标准I/O模型,Java提供了System.in, System.out System.err

String encoding = System.getProperty(“file.encoding”);

Charset.forName(encoding).decode(buff);

       tryLock(long position, long size, Boolean shared)

FileChannel fc = new FileOutputStream(“data2.txt”).getChannel();

       Static字段的序列化,用两个static方法:

 

9. 视图缓冲器

       视图缓冲器(view buffer)可以让我们经由过程某个特定的根基数据类型的视窗查看其底层的ByteBuffer. ByteBuffer依然是实际存储数据的地方,“支持”着前面的视图,因此,对视图的任何修改都会映照成为对ByteBuffer中数据的修改。

       Difference between filp() and rewind():

允许将内存的缓冲区当作InputStream使用

       Flip: flips this buffer. The limit is set to the current position and then the position is set to zero.If the mark is defined then it is discarded.

将其与FilterOutputStream工具相连以提供有用接口。

       “Big endian”(高位优先)将最重要的字节放在地址最低的存储器单元。而“little endian(低位优先)则是将最重要的字节放在地址最高的存储器单元。当存储量大于一个字节时,像int, float等,就要考虑字节的次序问题了。ByteBuffer是以高位优先的形式存储数据的,并且数据在网上传送时也常常使用高位优先的形式。我们可以使用带有参数ByteOrder.BIG_ENDIANByteOrder.LITTLE_ENDIANorder()方法改变ByteBuffer的字节排序方式。

Java I/O类库 - 自由之声 - 天涯在线的博客

 

6.标准I/O的意义在于:我们可以很容易地把程序串连起来,一个程序的标准输出可以成为另一个程序的标准输入。

ByteBuffer bb = ByteBuffer.wrap(new byte[12]);

       TimeUnit.MILLISECONDS.sleep(100);

System.out.println(Arrays.toString(bb.array()));

7. I/O

bb.order(ByteOrder.BIG_ENDIAN);

bb.asCharBuffer().put(“abcdef”);

  void  putFloat(float f)

bb.rewind();

 

或者

 

  void  putFloat(int index, float f)

 

10 内存映照文件

       内存映照文件允许我么创建和修改那些因为太大而不能放入内存的文件。有了内存映照文件,我们就可以假定整个文件都放在内存中,而且可以完全把它当作非常大的数组来接见。


Static int length = 0x8FFFFFF;

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

       MappedByteBuffer out = (new RandomAccessFile(“test.dat”, “rw”).getChannel().map(

              FileChannel.MapMode.READ_WRITE, 0 , length);

       For(int i = 0; i < length; i++)

              Out.put((byte)’x’);

       System.out.println(“Finished writing”);

       For(int i = length/2; i < length/2 + 6;i++)

     CharArrayWriter

 

MappedByteBufferByteBuffer继续而来,因此它具有ByteBuffer的所有方法。上述程序创建的文件为128MB,这可能比操纵系统所允许一次载入内存的空间大。但似乎我们可以一次接见到整个文件,因为只有一部分文件放入了内存,文件的其他部分被交换了出去。用这种方式,很大的文件(可达2GB)也可以很容易地修改。

If(fl != null) {

固然“旧”的I/O流在用nio实现后性能有所进步,但是“映照文件接见”往往可以更加显著地加快速度。

 

固然“映照读”似乎要用到FileInputStream, 但是映照文件中的所有输入必须使用RandomAccessFile

 

11. 文件加锁

文件锁对其他的操纵系统进程是可见的,因为Java的文件加锁直接映照到了本地操纵系统的加锁工具。

       Fl.release();

FileOutputStream fos = new FileOutputStream(“file.txt”);

FileLock fl = fos.getChannel().tryLock();

 

       System.out.println(“Locked File!”);

       对于Serializable工具,工具完全以它存储的二进制为基础来构造,而不调用构造器。而对于一个Externalizable工具,所有普通的默认构造器都会被调用(包括在字段定义时的初始化),然后调用readExternal().必须注意这一点-所有默认的构造器都会被调用,才能使Externalizable工具发生正确的行为。

       例如:

1.  File类可以查看目录及文件信息。一个有用的方法:renameTo可以将文件移动到另一个地方。

      PipedReader

       Public staic void main(String[] args)  throws Exception{

ReaderWriter这种字符模式类不能用于发生通讲;但是java.nio.channels.Channels类提供了实用方法,用以在通讲中发生ReaderWriter

       也可以使用如下方法对文件的一部分上锁:

A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations.

Buffer由数据和可以高效地接见及操纵这些数据的四个索引组成,这四个索引是:mark(标记) position(位置) limit(界限)capacity(容量)

       Lock(long position, long size, Boolean shared)

此中,加锁的区域由size-position决定。第三个参数指定是否是同享锁。

       固然无参数的加锁方法将根据文件尺寸的变化而变化,但是具有固定尺寸的锁不随文件尺寸的变化而变化。如果你获得了某一区域上的锁,当文件增大超出positon+size时,那么在position+size之外的部分不会被锁定。无参数的加锁方法会对整个文件进行加锁,甚至文件变大后也是如此。

       对独占锁或者同享锁的支持必须由底层的操纵系统提供。如果操纵系统不支持同享锁并为每一个请求都创建一个锁,那么它就会使用独占锁。锁的类型(同享或独占)可以经由过程FileLock.isShared()进行查询。

12. 工具序列化

工具序列化特别“聪明”的一个地方是它不仅保存了工具的“全景图”,而且能追踪工具内所包含的所有引用,并保存那些工具;接着又能对工具内包含的每个这样的引用进行追踪;依次类推。这种情况有时被称为“工具网”,单个工具可与之成立毗连,而且它还包含了工具的引用数组以及成员工具。

可经由过程实现Externalizable接口-替换实现Serializable接口-来对序列化过程进行控制。这个Externalizable接口继续了Serializable接口,同时增添了两个方法:writeExternal()readExternal().这两个方法会在序列化和反序列化还原的过程中被自动调用,以便执行一些特殊操纵。

具有“能弹出一个字节的缓冲区”,因此可以将读取到的最后一个字符回退。

JDK 1.4Java.nio.*包中引入了新的Java I/O类库,其目的在于进步速度。速度的进步来自于所使用的结构更接近于操纵系统执行I/O的方式:通讲和缓冲器。

      如果不是特别坚持实现Externalizable接口,那么还有另一种方法。我们可以实现Serializable接口,并添加名为writeObject()readObject()的方法。这样一旦工具被序列化或者被反序列化还原,就会自动地分别调用这两个方法。也就是说,只要我们提供了这两个方法,就会使用他们而不是默认的序列化机制。

System.out.println(bb.array());

Fc.write(ByteBuffer.wrap(“Some text”.getBytes(“UTF-16BE”)));

       serializeStaticState()deserializeStaticState(). 他们是作为存储和读取过程的一部分被显式地调用的。

13. Preferences

Preferences API与工具序列化相比,前者与工具持久性更稀切,因为它可以自动存储和读取信息。不过,它只能用于小的,受限的数据集合——我们只能存储根基类型和字符集,并且每个字符串的存储长度不能超过8K

例如:

Preferences prefs = Preferences.userNodeForPachage(PreferencesDemo.class);

Prefs.put(“Location”, “Oz”);

Prefs.getInt(“Companions”, 0);

 

注意get()的第二个参数,如果某个关键字下没有任何条目,那么这个参数就是所发生的默认值。


泰国人妖
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值