21xrx.com
2025-07-03 15:47:12 Thursday
登录
文章检索 我的文章 写文章
Java中写入文件的实现方法
2023-06-15 00:36:58 深夜i     17     0
Java 写入文件 FileOutputStream BufferedWriter PrintWriter

文章

在Java编程中,我们经常需要将数据写入文件中,以便于存储和持久化。Java提供了多种方式来实现文件写入,本文将介绍Java中写入文件的几种方法,并附上代码案例。

1. 使用FileOutputStream写入文件

FileOutputStream是Java IO中的一个输出流,用于将数据写入文件。下面是使用FileOutputStream写入文件的示例代码:

String fileName = "test.txt";
String data = "Hello World!";
try {
  FileOutputStream fos = new FileOutputStream(fileName);
  fos.write(data.getBytes());
  fos.close();
} catch (IOException e) {
  e.printStackTrace();
}

2. 使用BufferedWriter写入文件

BufferedWriter是Java IO中的一个字符输出流,用于将字符数据写入文件。下面是使用BufferedWriter写入文件的示例代码:

String fileName = "test.txt";
String data = "Hello World!";
try {
  FileWriter fw = new FileWriter(fileName);
  BufferedWriter bw = new BufferedWriter(fw);
  bw.write(data);
  bw.close();
} catch (IOException e) {
  e.printStackTrace();
}

3. 使用PrintWriter写入文件

PrintWriter是Java IO中的一个字符输出流,可以方便地将各种类型的数据格式化成字符串写入文件。下面是使用PrintWriter写入文件的示例代码:

String fileName = "test.txt";
String data = "Hello World!";
try {
  PrintWriter pw = new PrintWriter(fileName);
  pw.println(data);
  pw.close();
} catch (IOException e) {
  e.printStackTrace();
}

以上是Java中写入文件的三种方式,根据实际需要灵活选择。希望本文的例子能对大家在实际编程中有所帮助。

  
  

评论区