当前位置: 首页 > article >正文

练习-java输入输出之文件字节io流之合并文件

以下是一个示例Java程序,演示如何使用文件字节IO流合并两个文件:

import java.io.*;

public class FileMerger {
    public static void main(String[] args) {
        String file1 = "file1.txt";
        String file2 = "file2.txt";
        String mergedFile = "mergedFile.txt";

        try {
            FileInputStream fis1 = new FileInputStream(file1);
            FileInputStream fis2 = new FileInputStream(file2);
            FileOutputStream fos = new FileOutputStream(mergedFile);

            int byteRead;

            // 逐个字节读取两个文件,并将它们写入合并文件
            while ((byteRead = fis1.read()) != -1 && (byteRead = fis2.read()) != -1) {
                fos.write(byteRead);
                fos.write(byteRead);
            }

            // 将剩余的字节写入合并文件
            while (fis1.read() != -1) {
                fos.write(fis1.read());
            }
            while (fis2.read() != -1) {
                fos.write(fis2.read());
            }

            fis1.close();
            fis2.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们首先定义了要合并的两个文件名和合并后的文件名。然后,我们使用FileInputStream类从两个源文件中读取数据,并使用FileOutputStream类将它们写入合并文件中。在读取和写入数据时,我们使用了一个循环来逐个字节地处理数据。最后,我们关闭了所有的文件流。

当然,我们可以继续讨论Java中的文件操作。除了基本的读取和写入之外,Java还提供了许多其他的功能,比如读取文件的特定部分,追加数据到文件,移动或删除文件等。以下是一些其他的Java文件操作示例:

1. 使用RandomAccessFile类来读取文件的特定部分:

import java.io.*;

public class ReadSpecificPartOfFile {
    public static void main(String[] args) {
        try {
            RandomAccessFile file = new RandomAccessFile("example.txt", "r");
            file.seek(50); // 移动文件指针到文件的第50个字节处
            byte[] buffer = new byte[10];
            file.read(buffer); // 读取接下来的10个字节
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 使用FileWriter类向文件追加数据:

import java.io.*;

public class AppendToFile {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt", true);
            writer.write("This is some additional text.\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 使用File类来移动或删除文件:

import java.io.*;

public class ManageFile {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            if (file.delete()) {
                System.out.println("File deleted successfully.");
            } else {
                System.out.println("Failed to delete file.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这些只是一些基本的例子,Java的文件操作还包含很多其他的功能和复杂的场景。在处理文件时,请确保正确地处理异常,因为IO错误是常见的,并且你应该为这些错误做好准备。

4. 使用Scanner类从文件读取数据:

import java.io.*;
import java.util.*;

public class ReadDataFromFile {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(new File("example.txt"));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个示例展示了如何使用Scanner类逐行读取文件的内容。这对于处理包含文本数据的文件非常有用。

5. 使用BufferedReader类从文件读取行:

import java.io.*;
import java.util.*;

public class ReadLinesFromFile {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个示例展示了如何使用BufferedReader类逐行读取文件的内容。这种方法在处理大型文本文件时,相比使用Scanner会更高效。

6. 使用Files类进行文件的复制和移动:

import java.io.IOException;
import java.nio.file.*;

public class ManageFiles {
    public static void main(String[] args) {
        try {
            // 复制文件
            Path sourcePath = Paths.get("source.txt");
            Path targetPath = Paths.get("target.txt");
            Files.copy(sourcePath, targetPath);
            
            // 移动文件
            Files.move(sourcePath, targetPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7. 使用PrintWriter类和PrintStream类来写入格式化的数据:

import java.io.*;

public class FormatDataToFile {
    public static void main(String[] args) {
        try {
            PrintWriter writer = new PrintWriter("example.txt");
            writer.printf("Name: %s, Age: %d\n", "John", 25);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个示例展示了如何使用PrintWriter类和printf方法将格式化的数据写入文件。这种方法常用于写入人类可读的文本数据。

8. 使用DataOutputStream类来写入基本数据类型:

import java.io.*;

public class WriteDataToFile {
    public static void main(String[] args) {
        try {
            DataOutputStream dos = new DataOutputStream(new FileOutputStream("example.txt"));
            dos.writeInt(100);
            dos.writeDouble(100.5);
            dos.writeBoolean(true);
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个示例展示了如何使用DataOutputStream类来写入基本数据类型。这种方法常用于写入二进制数据。需要注意的是,写入的数据无法直接由人类阅读,但可以被其他Java程序读取。


9. 使用ObjectOutputStream类来写入对象:

import java.io.*;

public class WriteObjectToFile {
    public static void main(String[] args) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("example.txt"));
            Person person = new Person("John", 25);
            oos.writeObject(person);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个示例展示了如何使用ObjectOutputStream类来写入对象。这种方法常用于将对象的状态保存到文件中,然后在需要时重新加载。需要注意的是,对象必须实现Serializable接口才能被写入文件。

10. 使用FileInputStream类和InputStreamReader类来读取文件内容:

import java.io.*;
import java.nio.file.*;

public class ReadFileWithStreams {
    public static void main(String[] args) {
        try {
            Path path = Paths.get("example.txt");
            byte[] bytes = Files.readAllBytes(path);
            InputStream input = new ByteArrayInputStream(bytes);
            InputStreamReader reader = new InputStreamReader(input);
            char[] buffer = new char[1024];
            int len;
            while ((len = reader.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, len));
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个示例展示了如何使用Java的流来读取文件的内容。它首先读取文件的所有字节到一个字节数组中,然后通过InputStreamInputStreamReader和字符缓冲区来读取文件内容。这种方法适用于读取较小的文件,对于大型文件,建议使用逐行读取的方法。


http://www.kler.cn/news/160994.html

相关文章:

  • leetcode:93. 复原 IP 地址
  • 要求CHATGPT高质量回答的艺术:提示工程技术的完整指南—第 21 章:课程学习提示
  • 聊聊java的两种锁同步锁和重入锁
  • 【Element-ui】Layout与Container组件
  • Python版本与opencv版本的对应关系
  • FFmpeg之将视频转为16:9(横屏)或9:16(竖屏)(三十六)
  • BCI-Two-streams hypothesis(双流假说)
  • 2022年全国大学生数据分析大赛医药电商销售数据分析求解全过程论文及程序
  • Vector Quantized Diffusion Model for Text-to-Image Synthesis
  • 【高数:1 映射与函数】
  • DS1307时钟模块使用记录
  • C:算术移位和逻辑移位傻傻分不清楚
  • 智慧农业技术解决方案:PPT全文32页,附下载
  • 两种做法——判断是否是二叉搜索树
  • 【Proteus仿真】【STM32单片机】简易计算器
  • [ Linux Audio 篇 ] 音频开发入门基础知识
  • 什么是堆内存?参数如何设置?
  • 【LeetCode】2621. 睡眠函数
  • ETLCloud详解,如何实现最佳实践及问题排查
  • 代码随想录算法训练营第五十八天 | 793.每日温度,496.下一个更大元素 I
  • LabVIEW开发自适应降噪ANC
  • vue的propsData
  • 04 ECharts基础入门
  • MySQL和MongoDB简介以及它们之间的区别
  • ThinkPHP6使用Validate验证表单字段唯一
  • 【每日一题】重新规划路线
  • 【C++初阶】六、类和对象(初始化列表、static成员、友元、内部类)
  • 脉冲压缩及MATLAB仿真
  • 数组常用方法
  • 剧本杀小程序搭建:打造线上剧本杀新体验