Lessons Learn JavaIO: Files Write That

brief introduction

The little sister asked F brother a lot of strange requirements. To format the output, to specific code output, to locate the output yourself, what?Need to read and burn?Let's see how Brother F can recruit one by one.

Character and byte output

Young sister: Brother F, last time you talked about half of IO, file reading is basically finished, but the writing of the file has not been said yet. When will I give my little sister back to general science?

Young teacher and sister: Brother F, you know that I have always been a model of diligence and study, a good student in the eyes of teachers, a good example in the minds of students, and a good child by the side of my parents.When I am always climbing the peak of science, I find that half of the knowledge has not been acquired. It really makes me sigh, Brother F, pass on knowledge to me quickly.

Sister, younger brother, I should try my best to fulfill your request, but how do I remember how many days have passed since I last talked about IO file reading? Why did you come to me today?

Little sister with red face: Brother F, this is not the time to use encountered some problems, just want to find you to review your knowledge again.

More interesting and see:

Let's go through the structure of the output class again:

These are the two main output systems: Writer and OutputStream.

Writer is for characters and Stream is for Bytes.

The most common examples of Writer are FileWriter and BufferedWriter. Let's look at the next most basic writing example:

public void useBufferedWriter() 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 = new BufferedWriter(fw)){
            bw.write(content);
        }
    }

BufferedWriter is the encapsulation of FileWriter, which provides a buffer mechanism to improve the efficiency of writing.

BufferedWriter actually 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)

The first method passes in an int, the second method passes in an array of characters and the position and length at which to start reading, and the third method passes in a string and the position and length at which to start reading.Is it simple, completely understandable?

Little sister: No, Brother F, the parameters of the last two methods, char and String, are all characters I can understand. What is the ghost of the first method passing in int?

Little sister, did you forget what you told you before? The bottom storage of int is bytes, and the bottom storage of char and String is bytes. Let's just cast int and char.Let's see how this is converted:

public void write(int c) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (nextChar >= nChars)
                flushBuffer();
            cb[nextChar++] = (char) c;
        }
    }

Remember how many bytes int takes?Four, char takes up two bytes.Forcing the conversion from int to char will result in loss of precision, only two bytes of low-bit data will be retained, and two bytes of high-bit data will be discarded, which requires attention in use.

After watching Writer, let's take a look at Stream:

public void useFileOutputStream() 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);
        }
    }

Like Writer, BufferedOutputStream is also an encapsulation of FileOutputStream. Let's look at the write method provided in BufferedOutputStream:

public synchronized void write(int b)
public synchronized void write(byte b[], int off, int len)

Comparing with Writer, BufferedOutputStream's method is synchronized, and BufferedOutputStream operates directly on byte.

The first write method passed in the int parameter also needs to be intercepted, but this time it is converted from int to byte.

Format Output

Little sister: Brother F, what we often use System.out.println Formatted strings can be output directly to standard output. Does writing files have similar functions?

Certainly, PrintWriter is for formatted output:

public void usePrintWriter() 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("Program those things %s ", "Excellent");
        }
    }

Output Other Objects

Little sister: Brother F, we see that we can export String, char and Byte. Can't we export Integer,Long and other basic types?

Yes, you can do this with DataOutputStream:

public void useDataOutPutStream()
            throws IOException {
        String value = "www.flydean.com";
        try(FileOutputStream fos = new FileOutputStream("src/main/resources/www.flydean.com")){
            DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
            outStream.writeUTF(value);
        }
    }

DataOutputStream provides methods such as writeLong,writeDouble,writeFloat, and so on, as well as writeUTF!

Write at a specific location

Little sister: Brother F, sometimes we don't need to write from the beginning to the file every time. Can we customize where to write?

Using RandomAccessFile is OK:

public void useRandomAccess() throws IOException {
        try(RandomAccessFile writer = new RandomAccessFile("src/main/resources/www.flydean.com", "rw")){
            writer.seek(100);
            writer.writeInt(50);
        }
    }

RandomAccessFile can be located by seek and written from the specified location by the write method.

Lock Files

Little sister: Brother F, finally there is a problem. How can I ensure that no one else will overwrite my writing and there will be no conflict when I write a document?

FileChannel can invoke the tryLock method to obtain a FileLock lock through which we can control file access.

public void useFileLock()
            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();
        }
    }

summary

Today, I told my little sister a lot of ways to write documents, which is enough for her to learn for a while.

Examples of this article https://github.com/ddean2009/learn-java-io-nio

Author: Fldean Programs

Links to this article: http://www.flydean.com/io-file-writer/

Source: Fldean's blog

Welcome to my Public Number: program stuff, more exciting waiting for you!

Tags: Programming Spring Java github

Posted on Sun, 24 May 2020 18:57:35 -0400 by tillaart36