admin管理员组

文章数量:1609211

下面是一个FileOutputStream的一个学习例子,非常的简单,主要是把一个字符串写进一个名为text.txt的文件当中。主要用到的就是FileOutputStream的write(byte[] b)。代码如下:

   public static void main(String[] args) {
        FileOutputStream fileOutputStream = null;
        String path = FileInputStreamTest1.class.getResource("/data/test.txt").getPath();
        try {
            fileOutputStream = new FileOutputStream(path);
            String a = "abc";
            fileOutputStream.write(a.getBytes(StandardCharsets.UTF_8));
            //记得刷新
            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileOutputStream == null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

运行截图如下:


上面的代码把“abc”这个字符串写进了test.txt文件中。特别注意的是:使用输出流,要习惯性的加上flush()。

本文标签: IOFileOutputStream