java 文件输出流_Java 文件输出流

这篇Java IO教程详细介绍了如何使用FileOutputStream进行文件输出流操作。文章通过实例展示了如何创建输出流、处理异常、追加数据、写入字符串、插入新行以及关闭输出流。还提供了一个完整的代码示例,演示了如何将多行文本写入文件并确保数据正确刷新和关闭。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java IO教程 - Java文件输出流

创建输出流

要写入文件,我们需要创建一个FileOutputStream类的对象,它将表示输出流。// Create a file output stream

String destFile = "test.txt";

FileOutputStream fos = new FileOutputStream(destFile);

当写入文件时,如果文件不存在,Java会尝试创建文件。我们必须准备好处理这个异常,将代码放在try-catch块中,如下所示:try {

FileOutputStream fos = new FileOutputStream(srcFile);

}catch (FileNotFoundException e){

// Error handling code goes here

}

如果文件包含数据,数据将被擦除。为了保留现有数据并将新数据附加到文件,我们需要使用FileOutputStream类的另一个构造函数,它接受一个布尔标志,用于将新数据附加到文件。

要将数据附加到文件,请在第二个参数中传递true,使用以下代码。FileOutputStream fos = new FileOutputStream(destFile, true);

写数据

FileOutputStream类有一个重载的write()方法将数据写入文件。我们可以使用不同版本的方法一次写入一个字节或多个字节。

通常,我们使用FileOutputStream写入二进制数据。

要向输出流中写入诸如“Hello"的字符串,请将字符串转换为字节。

String类有一个getBytes()方法,该方法返回表示字符串的字节数组。我们给FileOutputStream写一个字符串如下:String text = "Hello";

byte[] textBytes = text.getBytes();

fos.write(textBytes);

要插入一个新行,使用line.separator系统变量如下。String lineSeparator = System.getProperty("line.separator");

fos.write(lineSeparator.getBytes());

我们需要使用flush()方法刷新输出流。fos.flush();

刷新输出流指示如果任何写入的字节被缓冲,则它们可以被写入数据宿。

关闭输出流类似于关闭输入流。我们需要使用close()方法关闭输出流。// Close the output stream

fos.close();

close()方法可能抛出一个IOException异常。如果我们希望自动关闭tit,请使用try-with-resources创建输出流。

以下代码显示如何将字节写入文件输出流。import java.io.File;

import java.io.FileOutputStream;

public class Main {

public static void main(String[] args) {

String destFile = "luci2.txt";

// Get the line separator for the current platform String lineSeparator = System.getProperty("line.separator");

String line1 = "test";

String line2 = "test1";

String line3 = "test2";

String line4 = "test3";

try (FileOutputStream fos = new FileOutputStream(destFile)) {

fos.write(line1.getBytes());

fos.write(lineSeparator.getBytes());

fos.write(line2.getBytes());

fos.write(lineSeparator.getBytes());

fos.write(line3.getBytes());

fos.write(lineSeparator.getBytes());

fos.write(line4.getBytes());

// Flush the written bytes to the file fos.flush();

System.out.println("Text has been written to "

+ (new File(destFile)).getAbsolutePath());

} catch (Exception e2) {

e2.printStackTrace();

}

}

}

上面的代码生成以下结果。

5ba9d2eb2e140580eb13a02959eea5ee.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值