Home > 类库下载 > java类库 > Three methods of Java file I/O

Three methods of Java file I/O

高洛峰
Release: 2016-10-12 17:53:31
Original
1974 people have browsed it

I was asked twice in the interview how to write the file reading and output in Java. At that time, I only remembered a rough idea and couldn't explain it clearly. Today I specially summarized this aspect. I want to Write it down and share it with everyone.

First of all, there are three commonly used file reading and output streams: FileInputStream/FileOutputStream, FileReader/FileWriter, and RandomAccessFile. Here are some simple examples for reference:

Basic article:

1.

FileRead fr = new FileReader(filename);  
String s;  
while( (s=fr.readLine())!=null){  
...  
}  
fr.close();  
//FileWriter同理,输出时可用write()函数  
//Java I/O中所有的Reader、Writer都是面向字符流的输出输出
Copy after login

2.

FileInputStream fi =new FileInputStream(filename);  
int in;  
while( (in=fi.read())!=-1){  
...  
}  
fi.close();  
//FileOutputStream同理  
//Java I/O中所有的Reader、Writer都是面向字节流的输出输出
Copy after login

3.

RandomAccessFile ra =new RandomAccessFile(filename,"rw");//后面的参数指定的是  
打开文件流的方式,“rw”是指读写,“r”是只读,Java不提供只写  
ra.seek(number);//将文件指针移动到number处,这里文件指针可以理解为文件开始读的位置  
ra.skipByte(number);//跳过number个字节  
ra.read();  
ra.close();  
//RandomAccessFile既可以读也可以写,而且可以利用seek()函数指定位置
Copy after login

The following are some introductions from Baidu Encyclopedia:

RandomAccessFile does not belong to the InputStream and OutputStream classes Department. In fact, except for implementing the DataInput and DataOutput interfaces (DataInputStream and DataOutputStream also implement these two interfaces), it has nothing to do with these two classes, and it does not even use the functions that InputStream and OutputStream have prepared; it is A completely independent class, all methods (most of which belong to itself) are written from scratch. This may be because RandomAccessFile can move forward and backward within the file, so its behavior is fundamentally different from other I/O classes. All in all, it is an independent class that directly inherits Object.

Advanced:

In nio, Java re-implements the I/O stream and introduces some new methods to improve speed. I mainly introduce channels and memory mapped files

1. Channel:

Channel and buffer are a paired concept. An example in Thinking in Java is particularly easy to understand: we treat the file we want to read as a coal mine , data is the coal we want. The channel is like a conveyor belt that transports coal. We have no way to take the coal directly from the conveyor belt, so we have to use trucks to load the coal. The truck is the buffer. It is mainly responsible for taking out the data from the channel and passing it to the program we wrote. The only buffer that can interact with channels is ByteBuffer. It can be seen that the way to parse streams supported by channels is byte streams. So it uses FileInputStream/FileOutputStream, RandomAccessFile

Example:

a.

FileChannel fc =new FileOutputStream(filename).getChannel();  
fc.write(ByteBuffer.wrap("something test".getBytes() ));//这里使用ByteBuffer比较简单,其实ByteBuffer可以利用个put()函数写入byte数组  
fc.close();
Copy after login

b.

fc= new FileOutputStream(filename).getChannel();  
ByteBuffer buff = ByteBuffer.allocate(size);//没错,ByteBuffer是不提供显示构造函数的,想要新建一个对象必须利用allocate()函数来分配空间。  
fc.read(buff);  
fc.close();
Copy after login

Why do you think of using channels for I/O? The main consideration is performance issues, channels plus buffers It allows the program to read and write a certain amount of characters, while using only InputStream/OutputStream, Reader/Writer can only read and write one byte/character at a time. When the program performs I/O, it must be handed over to the operating system to solve this part of the function (calling system calls). Reducing the number of times handed over to the operating system can effectively reduce the time spent on I/O

2. Memory mapping file:

The main meaning of memory mapped files is actually that the files are put into the memory and accessed as a very large array, which is very efficient. Why is it better? This starts with the Java virtual machine and operating system (Actually, I don’t understand it very well. I just read an article that explained it clearly. The link is http://www.360doc.com/content ...) This article mainly introduces the principles of Java I/O and the principles of memory mapped files. Let me try to summarize: the main implementation method of Java I/O is definitely to use system calls, and the system calls first transfer the files you want to use from the hard disk to the I/O buffer of the kernel. This time, the Java program will be imported. You want more content in the file (copying more content is because of the locality principle of the program, which can achieve better efficiency), and then import it from the kernel's I/O buffer into the Java process's own private memory space. middle. The memory mapped file abandons the method of two copies and directly forms a mapping between the virtual space of the Java process and the file object. When the desired content cannot be found in the private memory space, a page fault exception occurs, and then the lower-level system is used. Call to solve this problem (in fact, page fault exception handling is also involved in I/O system calls). The advantage is that it reduces the overhead from the kernel I/O buffer to the process private address.

Example:

FileChannel fc = new RandomAccessFile(filename,"rw").getChannel();  
MappedByteBuffer mb = fc.map(FileChannel.MapMode.READ_WRITE,start,length);  
mb.put((byte)'x');  
mb.get();  
fc.close();
Copy after login

Writing this, I suddenly thought of the 4 ways to write "fennel" in "Kong Yiji". Now there are at least five ways to open files in Java, each of which has its own advantages and disadvantages. From now on, you can also wear a robe and ask others if you know the 5 ways to read and write files in Java

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template