Using IO stream to write files

Keywords: Java Apache Maven github nexus

Preface

When it is necessary to operate on files, it is inevitable to use IO flow; for example, some contents in the response results of some requests need to be stored in the business. When the file to be processed is too large, if you close the file stream frequently, it will cause a lot of overhead. When do you close it? It often causes great trouble. So how can we handle the files more elegantly?

Use cases

scene

When storing data, enter is used to separate rows; Tab is used to separate data fields of a row

Code address

https://github.com/mmzsblog/IO-demo

Solution 1:

Using IOUtil, a tool class provided by apache, can deal with this problem conveniently and quickly. This tool class encapsulates many methods

  • Dependency package of introducing apache tool class IOUtil
    <dependencies>
        <!-- apache One provided IO Tool class -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
  • The main codes are as follows:
public static void main(String[] args) {

    List<String> list = new ArrayList();
    list.add("hello");
    list.add("third");
    list.add("method");
    list.add("io");
    list.add("util");
    OutputStream os = null;
    File filePath = new File("d:\\" + DateUtil.getCurrentDate("yyyyMMdd") + ".txt");

    try {
        os = new FileOutputStream(filePath, true);
        //The fields in a row are separated by tab s
        IOUtils.writeLines(list,"\t",os);
        //Rows are separated by carriage returns
        IOUtils.write("\n", os);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Solution 2:

  • The main codes are as follows:
    public static void main(String[] args) {

        File filePath = new File("d:\\" + DateUtil.getCurrentDate("yyyyMMdd") + ".txt");

        //Save data to StringBuffer and then to file
        List<String> list = new ArrayList();
        list.add("hello");
        list.add("second");
        list.add("method");
        list.add("io");
        list.add("util");
        //Because thread safety is not involved here, StringBuilder is used
        StringBuilder sb = new StringBuilder();
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            sb.append(item).append("\t");
        }
        String newTxt = sb.deleteCharAt(sb.length()-1).append("\n").toString();

        BufferedWriter bw = null;
        try {
            //true indicates that the file is written in append mode; flash indicates that the file is overwritten
            bw = new BufferedWriter(new FileWriter(filePath, true));
            bw.write(newTxt);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != bw) {
                try {
                    bw.flush();
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Solution 3:

  • The main codes are as follows:
public class IOFirst {

    /**
     * description: It's the most complicated, but also a relatively test of basic skills
     * author: mmzsit
     * date: 2018/12/27 17:45
    */
    public static void main(String[] args)
    {
        File log=new File("d:\\"+DateUtil.getCurrentDate("yyyyMMdd") +".txt");
        List<String> list = new ArrayList();
        list.add("hello");
        list.add("first");
        list.add("method");
        list.add("io");
        list.add("util");
        //Because thread safety is not involved here, StringBuilder is used
        StringBuilder sb = new StringBuilder();
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            sb.append(item).append("\t");
        }
        String newLog = sb.deleteCharAt(sb.length()-1).toString();
        //Call appendLog method to perform file write operation
        appendLog(log,newLog);
    }

    /**
     * description: This method is a self written class. How do you want to operate it according to your own meaning
     * author: mmzsit
     * date: 2018/12/27 17:42
    */
    public static void appendLog(File filePath,String newTxt)
    {
        Scanner sc=null;
        PrintWriter pw=null;
        try{
            isExists(filePath);
            sc=new Scanner(filePath);
            StringBuilder sb=new StringBuilder();
            //First, read out the contents of the old file and save it in sb;
            while(sc.hasNextLine())
            {
                sb.append(sc.nextLine());
                //The scanner cannot read the newline as an interval, so add it by yourself
                sb.append("\t\n");
            }
            if (0 != sb.length()) {
                //Resolve every extra blank line
                sb.deleteCharAt(sb.length()-1);
            }
            sc.close();

            pw=new PrintWriter(new  FileWriter(filePath),true);
            //A. write the contents of the old file
            pw.println(sb.toString());
            //B. write new file contents
            pw.println(newTxt);
            /*
             * If you write A first, the most recent write is at the end of the file
             * If write B first, the most recent write is in front of the file
             */
            pw.close();
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }

    /**
     * description: Ensure the existence of folders
     * author: mmzsit
     * date: 2018/12/27 17:42
    */
    public static void isExists(File filePath){
        //If the file does not exist, create a new one
        if(!filePath.exists())
        {
            File parentDir=new File(filePath.getParent());
            //If the directory does not exist, create a new one
            if(!parentDir.exists()) {
                parentDir.mkdirs();
            }
            try {
                filePath.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Posted by SkyRanger on Mon, 02 Dec 2019 09:16:12 -0800