[Java] What should I use for writing files?

background

There are many classes for reading and writing files, but I didn't know which class was best to use. In the old days, I used to refer to the code in another project ~~ copy ~~. So I looked it up. In conclusion, the more I looked up, the more confused I was. And use this! !! I didn't find anything like that.

What is Stream?

Process the data in bytes. ~~ By the way, there is no class called Stream. ~~ interface https://docs.oracle.com/javase/jp/8/docs/api/java/util/stream/Stream.html

InputStream A class that does ** "read" ** with bytes.

OutputStream A class that does ** "write" ** with bytes.

FileInputStream A class for reading bytes. A child class of InputStream. It's quite old.

FileOutputStream A class for writing bytes. A child class of OutputStream. It's quite old.

InputStreamReader The role of passing the InputStream to the Reader. Specify the character code here.

OutputStreamWriter The role of passing the Output Stream to the Writer. Specify the character code here.

Reader Do ** "read" ** from the stream in character units (char [] in code) instead of bytes.

Writer Do ** "write" ** from the stream in character units (char [] in code) instead of bytes.

What is buffering?

A function that stores in memory and reads and writes at once when a certain amount is accumulated. As a result, the performance of reading and writing byte by byte is good.

BufferedReader With Reader buffering function

BufferedWriter With Writer buffering function

I tried to implement the file writing function

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FileCreate {
    public static void main(String[] args) {

        //File path to read and write
        Path path = Paths.get("C:\\demo.txt");
        //Character string to write
        List<String> lines = Stream.of("AIUEO", "Kakikukeko", "SA Shi Su Se So").collect(Collectors.toList());

        //File writing 1
        //Character code is UTF by default-8
        //I'm using OutputStreamWriter
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            for (String str : lines) {
                //Note that if you pass null, it will be written as a character string called null.
                writer.append(str);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //File writing 2
        //Internally uses BufferedWriter, OutputWriter and FileOutputStream
        try {
            //When you want to write a new one
            Files.write(path, lines, Charset.forName("Shift_JIS"), StandardOpenOption.WRITE);
            //When you want to add
            Files.write(path, lines, Charset.forName("Shift_JIS"), StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //File writing 3
        // printWriter
        try (
            //True if you want to add, false if new
            FileOutputStream fileOutputStream = new FileOutputStream(path.toFile(), true);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, Charset.forName("Shift_JIS"));
            PrintWriter printWriter = new PrintWriter(outputStreamWriter)) {

            for (String s : lines) {
                printWriter.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //File writing 4
        // BufferedWriter
        try (
            //True if you want to add, false if new
            FileOutputStream fileOutputStream = new FileOutputStream(path.toFile(), true);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, Charset.forName("Shift_JIS"));
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {

            for (String s : lines) {
                bufferedWriter.append(s);
                bufferedWriter.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If you want to keep it simple, I think you can write file 1 or 2. However, if you want to customize the writing contents to your liking, I will use file writing 3 or 4.

File writing 3 and 4 are easy for me to understand and declare variables one by one. Of course, it's OK to put them together in one line.

new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path.toFile(), true), Charset.forName("Shift_JIS")));

One thing to keep in mind is that you don't forget close ().

At the end

I spent about two days researching it, but I could roughly understand it. However, I feel that I do not understand the details. If it's wrong, or is this code useless? I would appreciate it if you could point out any points.

Recommended Posts

[Java] What should I use for writing files?
What should I use for the testing framework [Rails]
Use only for writing files --Apache Camel
I made a Diff tool for Java files
What I researched about Java 8
What I researched about Java 9
What I researched about Java 7
[Java] Tips for writing source
What I researched about Java 5
java (use class type for field)
Reading and writing Java basic files
What I learned with Java Gold
What I learned with Java Silver
What I researched about Java learning
How to use binding.pry for view files
Java for All! I read everyone's Java #minjava
I tried Cassandra's Object Mapper for Java
Learn Java with "So What" [For beginners]
[Java] Reading and writing files with OpenCSV
What I learned from Java monetary calculation
Reading and writing gzip files in Java
I want you to use Scala as Better Java for the time being
I studied for 3 weeks and passed Java Bronze
Use Java7 try-with-resources statement for Cursor close processing
I want to use java8 forEach with index
What is the volatile modifier for Java variables?
What I learned in Java (Part 2) What are variables?
After all, how should I use Rails callback?
What I did when I converted java to Kotlin
Use Java external library for the time being
Let's use Java New FileIO! (Introduction, for beginners)
[Review] Reading and writing files with java (JDK6)
What is java
For JAVA learning (2018-03-16-01)
What is Java <>?
2017 IDE for Java
What is Java
What i learned
[Java] Use Collectors.collectingAndThen
Java for statement
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
What should I do to reload the updated Dockerfile?
How to use Truth (assertion library for Java / Android)
What I learned in Java (Part 3) Instruction execution statement
What I learned when building a server in Java
I tried using an extended for statement in Java
What Java engineers need to prepare for the Java 11 release
I tried to chew C # (reading and writing files)
I tried to find out what changed in Java 9
What should I do after January 2019 regarding the Java payment issue and Java 8 end of support issue?
docker What should I do first? (Somehow I understand the shell, but ... for beginners at the level)