Java-通过FileOutputStream写文件

Java-通过FileOutputStream写文件

Tags: Java

摘要

Java-通过FileOutputStream写文件

FileOutputStream写入文件

在Java中,FileOutputStream是的用来处理原始二进制数据的字节流类。要写入文件中的数据,必须将数据转换成字节,然后讲其保存到文件中。请参见下面完整的例子。

package cn.javacore.io.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

        FileOutputStream fop = null;
        File file;
        String content = "This is the text content";

        try {
            file = new File("/home/zhu/newfile.txt");
            fop = new FileOutputStream(file);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            // get the content in bytes
            byte[] contentInBytes = content.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

优化资源处理

try resource close 自动释放资源

package cn.javacore.io.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

        File file = new File("/home/zhu/newfile.txt");
        String content = "This is the text content";

        try (FileOutputStream fop = new FileOutputStream(file)) {

            // if file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            // get the content in bytes
            byte[] contentInBytes = content.getBytes();

            fop.write(contentInBytes);
            fop.flush();
            fop.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

代码下载

https://coding.net/u/javacore/p/java-io-study/git