如何在 Java 中从一个文件读取数据并打印到另一个文件?

java 8object oriented programmingprogramming更新于 2025/6/27 1:07:17

Java 提供了 I/O 流来读写数据,其中 Stream 表示输入源或输出目标,输出目标可以是文件、I/O 设备、其他程序等。

通常,Stream 可以是输入流或输出流。

  • InputStream − 用于从源读取数据。

  • OutputStream − 用于将数据写入目标。

根据它们处理的数据,流分为两种类型 −

  • 字节流 −这些以字节(8 位)为单位处理数据,即字节流类读取/写入 8 位数据。您可以使用这些类存储字符、视频、音频、图像等。

  • 字符流 − 这些类处理 16 位 Unicode 数据。使用它们,您只能读取和写入文本数据。

下图展示了 Java 中的所有输入和输出流(类)。

其中,您可以使用 Scanner、BufferedReader 和 FileReader 类读取文件内容。

同样,您可以使用 BufferedWriter、FileOutputStream 和 FileWriter 将数据写入文件。

将一个文件的内容写入另一个文件

以下 Java 程序使用 Scanner 类将数据从文件读取到字符串,并将其写入使用 FileWriter 类的另一个文件。

示例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class CopyContent {
   public static void main(String[] args) throws IOException {
      //实例化文件类
      File file = new File("D:\sampleData.txt");
      //实例化 FileInputStream 类
      FileInputStream inputStream = new FileInputStream(file);
      //实例化 Scanner 类
      Scanner sc = new Scanner(inputStream);
      //用于存储内容的 StringBuffer
      StringBuffer buffer = new StringBuffer();
      //将每一行追加到缓冲区
      while(sc.hasNext()) {
         buffer.append(" "+sc.nextLine());
      }
      System.out.println("文件内容: "+buffer);
      //创建一个 File 对象来保存目标文件
      File dest = new File("D:\outputFile.txt");
      //实例化一个 FileWriter 对象
      FileWriter writer = new FileWriter(dest);
      //将内容写入目标
      writer.write(buffer.toString());
      writer.flush();
      System.out.println("File copied successfully.......");
   }
}

输出

文件内容: Tutorials Point originated from the idea that there exists a 
class of readers who respond better to online content and prefer to learn new skills 
at their own pace from the comforts of their drawing rooms. The journey commenced 
with a single tutorial on HTML in 2006 and elated by the response it generated, 
we worked our way to adding fresh tutorials to our repository which now proudly 
flaunts a wealth of tutorials and allied articles on topics ranging from programming 
languages to web designing to academics and much more. 40 million readers read 100 
million pages every month. Our content and resources are freely available and we prefer 
to keep it that way to encourage our readers acquire as many skills as they would like to. 
We don’t force our readers to sign up with us or submit their details either. 
No preconditions and no impediments. Simply Easy Learning!
File copied successfully.......

相关文章