Java I/O 教程(三) FileOutputStream类

Java FileOutputStream 用于将字节数据写入文件。

如果你需要将原始数据写入文件,就使用FileOutputStream类。

Java.io.FileOutputStream class声明如下:

public class FileOutputStream extends OutputStream 

构造函数

FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.

FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.

FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.

常用函数

void write(byte[] ary)                        往文件输出流写指定字节数组
void write(byte[] ary, int off, int len)    往文件输出流写指定长度字节数组
void write(int b)                            往文件输出流写指定字节
void close()                                关闭文件输出流

例子1:

package com.dylan.io;

import java.io.FileOutputStream;

/**
 * @author xusucheng
 * @create 2017-12-31
 **/
public class FileOutputStreamWriteByte {
    public static void main(String[] args) {
        try {
            FileOutputStream fout = new FileOutputStream("D:\\testout.txt");
            fout.write(65);
            fout.close();
            System.out.println("success...");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}


例子2:

package com.dylan.io;

import java.io.FileOutputStream;

/**
 * @author xusucheng
 * @create 2017-12-31
 **/
public class FileOutputStreamWriteString {
    public static void main(String[] args) {
        try {
            FileOutputStream fout = new FileOutputStream("D:\\testout.txt",true);
            String s = "Welcome to java.io.";
            byte b[] = s.getBytes(); //将字符串转为字节数组
            fout.write(b);
            fout.close();
            System.out.println("写入成功!");
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }
}


测试效果截图:


执行例子1:

执行例子2:




下一章:

Java I/O 教程(四) FileInputStream 类




posted @   一锤子技术员  阅读(4)  评论(0编辑  收藏  举报  
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示