Common usage of IO
1) Find files in opposite paths. new File(file)
2) Turn files into output streams. FileOutPutStream();
-
Bufferedoutputstream improves file write speed, buffering. bufferedoutputstream.
-
Process the data. dataoutputstream.
Second, decoration mode
Component: Abstract build interface
ConcreteComponent: Concrete build objects that implement component object interfaces, usually decorated primitives. Add functionality to this object.
Decorator: An abstract parent class of all decorators that defines an interface consistent with the Component interface and holds a Component object inside.
ConreteDecoratorA/ConreteDecoratorB: actual decorator object, to achieve specific add functionality.
Decorator mode in IO
1. Byte stream (English)
1) inputStrem is an interface.
2) Classes that inherit from inputStream implement the read method, which is the object that concretely fetches the data stream.
3) The actual decorator object is the object that needs to be passed in to fetch the stream data. It’s just dealing with convection.
2. Character stream (Chinese characters)
A Writer – > FilterWriter – > BufferedWriter – > OutputStreamWriter – > FileWriter – > other
OutputStreamWrite can fill in encoding modes.
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(
new File("src/testtxt/writerAndStream.txt")),"GBK"));
Copy the code
FileWrite and FileRead encapsulate the following code.
new OutputStreamWriter(new FileOutputStream(new File("src/testtxt/writerAndStream.txt")),"GBK"));
Copy the code
File and RandomAccessFile
file
You can only read them in order.
RandomAccessFile
RandomAccessFile raf = newRandomAccessFile(File File, String mode); “R” : readable, “w” : writable, “rw” : readable.
You can read it from anywhere.
1) Seek method, will not change the file length. Reads and writes start from the next position.
2) setLength method, will change the file size. But it doesn’t change where it’s written, it’s written from scratch.
3) Usage scenario, breakpoint continuation of network data.
Nio FileChannel
Method of use
FileOutPutStream has a channel in it.
FileChannel sourceFileChannel = randomAccessSourceFile.getChannel();
FileChannel targetFileChannel = randomAccessTargetFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024*1024);
try {
while(sourceFileChannel.read(byteBuffer) ! = -1) {
byteBuffer.flip();// Set position to the end and limit to the maximum position to read
targetFileChannel.write(byteBuffer);
byteBuffer.clear();/ / position, limit, Capacity is set to the initial position.}}catch (Exception e) {
e.printStackTrace();
} finally {
try {
sourceFileChannel.close();
} catch (Exception e2) {
e2.printStackTrace();
}
try {
targetFileChannel.close();
}catch(Exception e) { e.printStackTrace(); }}Copy the code