1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with...

6
1 Chapter 10: Writing Files

Transcript of 1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with...

Page 1: 1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with no specific information about its structure Common.

1

Chapter 10: Writing Files

Page 2: 1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with no specific information about its structure Common.

2

Basic Information• You can regard the file as a series of

bytes with no specific information about its structure

• Common file extension give us some clues about the file internal structure

• Two Modes of accessing file:– Sequential access– Random access

Page 3: 1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with no specific information about its structure Common.

3

• Why: They are very efficient, because they use OS buffers

• A file channel object defines a channel for a physical file

• You can create a file channel object using “fileOutputStream.getChannel()”

• All the channel related classes and interfaces are found in java.nio.channels

File Channels

Page 4: 1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with no specific information about its structure Common.

4

File Channels (Cont.)

Your program

Buffer Object

File Stream Object

Channel Object

Page 5: 1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with no specific information about its structure Common.

5

• Almost all classes inherit from the Buffer class. They are found in java.nio

• ByteBuffer is the only one used in I/O• Viewer Buffers as CharBuffer, Double, etc.• Buffer capacity, position, and limit {capacity(),

position(), limit(), remaining(), hasRemaining()}• Buff.limit(512).position(256)• ByteBuffer buff = ByteBuffer.allocate(1024);• IntBuffer intBuf = buf.asIntBuffer();• ByteBuffer buf = ByteBuffer.wrap(str.getBytes());• Relative put/get and absolute put/get

The Buffer Class

Page 6: 1 Chapter 10: Writing Files. 2 Basic Information You can regard the file as a series of bytes with no specific information about its structure Common.

6

• Putting data relatively in a view buffer only update the position of the view buffer NOT the backing buffer

• Write data to a file both position and limit should be set properly buf.limit(but.position()).position(0) = buf.flip();

• Ex: WriteAString.java• WriteAStringAsBytes.java• WriteProverbs.java• PrimesToFile.java & PrimeToFile2.java

The Buffer Class (Cont)