Introduction to the
The little sister also raised a lot of strange requirements to brother F, to format the output, to specific coding output, to locate the output, what? And burn after reading? We see how brother F one by one take it.
Character output and byte output
Brother F, in the middle of your IO lecture last time, you basically finished reading the file, but you haven’t talked about the writing of the file yet. When will YOU give me another popular science?
Junior sister: Brother F, you know THAT I have always been a model of diligence and learning. I am a good student in the eyes of teachers, a good example in the hearts of classmates, and a good boy around my parents. When I climb the peak of science, I find that half of the knowledge has not been acquired. It really makes me sigh with regret. Brother F, pass the knowledge to me quickly.
I will do my best to fulfill your request, but I remember that it has been several days since I talked about IO file reading last time. Why did you come to me today?
Little sister blushing: brother F, this is not the use of the time encountered some problems, just want to find you to review the knowledge again.
More highlights:
- Blockchain from getting started to Giving up series tutorials – with ongoing updates covering cryptography, Hyperledger, Ethereum,Libra, Bitcoin and more
- Spring Boot 2.X Series tutorials: Learn Spring Boot from Scratch in seven days – continuous updates
- Spring 5.X Series tutorials: Everything you can think of in Spring5 – constantly updated
- Java Programmer from Handyman to Expert to God (2020 edition) – Ongoing updates with detailed articles and tutorials
Let’s go over the structure of the output class again:
These are the two main output systems: Writer and OutputStream.
Writer is for characters, while Stream is for Bytes.
FileWriter and BufferedWriter are the most commonly used writers. Let’s look at the next basic write example:
public void useBufferedWriter(a) throws IOException {
String content = "www.flydean.com";
File file = new File("src/main/resources/www.flydean.com");
FileWriter fw = new FileWriter(file);
try(BufferedWriter bw = newBufferedWriter(fw)){ bw.write(content); }}Copy the code
BufferedWriter encapsulates FileWriter and provides a buffer mechanism to improve write efficiency.
BufferedWriter provides three ways to write:
public void write(int c)
public void write(char cbuf[], int off, int len)
public void write(String s, int off, int len)
Copy the code
The first method passes in an int, the second method passes in an array of characters and the position and length to start reading, and the third method passes in a string and the position and length to start reading. Isn’t it simple and totally understandable?
Char (int) : char (int) : char (int) : char (int) : char (int) : char (int) : char (int) : char (int) : char (int) : char (int) : char (int) : char (int) : char (int)
Bytes are the underlying storage of int, and bytes are the underlying storage of char and String. We can cast int and char. Let’s see how this works:
public void write(int c) throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar >= nChars)
flushBuffer();
cb[nextChar++] = (char) c; }}Copy the code
Remember how many bytes int takes? Four. Char takes up two bytes. Forcing a conversion from int to char causes a loss of precision. Only the lowest 2 bytes of data will be retained, and the highest 2 bytes will be discarded.
After watching Writer, let’s look at Stream:
public void useFileOutputStream(a) throws IOException {
String str = "www.flydean.com";
try(FileOutputStream outputStream = new FileOutputStream("src/main/resources/www.flydean.com");
BufferedOutputStream bufferedOutputStream= new BufferedOutputStream(outputStream)){
byte[] strToBytes = str.getBytes(); bufferedOutputStream.write(strToBytes); }}Copy the code
Like Writer, BufferedOutputStream encapsulates FileOutputStream. Let’s take a look at the write methods provided by BufferedOutputStream:
public synchronized void write(int b)
public synchronized void write(byte b[], int off, int len)
Copy the code
The BufferedOutputStream method is synchronized, and BufferedOutputStream operates directly on byte.
The first write method that passes an int argument also needs to be intercepted, but this time it is converted from int to byte.
Formatted output
F: The system.out. println can directly output the formatted string to the standard output. Is there a similar function for file writing?
PrintWriter is used to format output:
public void usePrintWriter(a) throws IOException {
FileWriter fileWriter = new FileWriter("src/main/resources/www.flydean.com");
try(PrintWriter printWriter = new PrintWriter(fileWriter)){
printWriter.print("www.flydean.com");
printWriter.printf("The program thing %s"."It's great."); }}Copy the code
Output other objects
F: We can output String, char, and Byte. Can we output Integer,Long, and other basic types?
This can be done using DataOutputStream:
public void useDataOutPutStream(a)
throws IOException {
String value = "www.flydean.com";
try(FileOutputStream fos = new FileOutputStream("src/main/resources/www.flydean.com")){
DataOutputStream outStream = new DataOutputStream(newBufferedOutputStream(fos)); outStream.writeUTF(value); }}Copy the code
DataOutputStream provides writeLong writeDouble, writeFloat method and so on, can also be writeUTF!
Write at a specific location
Brother F, sometimes we don’t need to write to the file from the beginning every time. Can we customize where to write?
Just use RandomAccessFile:
public void useRandomAccess(a) throws IOException {
try(RandomAccessFile writer = new RandomAccessFile("src/main/resources/www.flydean.com"."rw")){
writer.seek(100);
writer.writeInt(50); }}Copy the code
RandomAccessFile can be located by seek and then written from the specified location using the write method.
Lock the file
Brother F, there is one last question. How can I guarantee that others will not overwrite what I have written when I am writing a document, and there will be no conflict?
FileChannel can call the tryLock method to obtain a FileLock lock through which we can control access to the file.
public void useFileLock(a)
throws IOException {
try(RandomAccessFile stream = new RandomAccessFile("src/main/resources/www.flydean.com"."rw");
FileChannel channel = stream.getChannel()){
FileLock lock = null;
try {
lock = channel.tryLock();
} catch (final OverlappingFileLockException e) {
stream.close();
channel.close();
}
stream.writeChars("www.flydean.com"); lock.release(); }}Copy the code
conclusion
Today, I told my junior sister many ways to write documents, which was enough for her to learn for a while.
Examples of this article github.com/ddean2009/l…
Author: Flydean program stuff
Link to this article: www.flydean.com/io-file-wri…
Source: Flydean’s blog
Welcome to pay attention to my public number: procedures those things, more wonderful waiting for you!