深入理解Java中的IO流:读写文件示例

原创 た 入场券 2024-12-01 21:27 171阅读 0赞

在Java中,I/O(Input/Output)流是用于处理输入和输出的抽象类。其中最常用的是FileInputStream和FileOutputStream。

下面是一个简单的读写文件的示例:

  1. 创建文件

    1. // 创建一个新文件
    2. File file = new File("test.txt");
    3. // 如果文件不存在,尝试创建它
    4. if (!file.exists()) {
    5. file.createNewFile();
    6. System.out.println("File created successfully.");
    7. } else {
    8. System.out.println("File already exists.");
    9. }
  2. 读写文件

    1. // 1. 使用 FileInputStream 读取文件
    2. FileInputStream fis = new FileInputStream(file);
    3. try {
    4. byte[] data = new byte[1024]; // 每次读取1KB数据
    5. int count = 0;
    6. while (fis.read(data) != -1) { // 当有数据可读时
    7. System.out.print(new String(data, 0, count)) + " "); // 输出读取到的数据
    8. count += data.length; // 更新已读数据长度
    9. }
    10. } finally {
    11. fis.close(); // 关闭文件输入流,释放资源
    12. }
  3. 写入文件

    1. // 2. 使用 FileOutputStream 写入文件
    2. FileOutputStream fos = new FileOutputStream(file);
    3. try {
    4. byte[] data = "Hello, World!".getBytes(); // 要写入的数据
    5. fos.write(data); // 将数据写入文件
    6. } finally {
    7. fos.close(); // 关闭文件输出流,释放资源
    8. }

以上就是Java中使用IO流读写文件的基本步骤。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,171人围观)

还没有评论,来说两句吧...

相关阅读