Java -- 对一个文件的任意位置可以插入任何内容

题目:提供一个文件操作的方法,其需要实现功能:对一个文件的任意位置可以插入任何内容
提供一个文件操作的方法,其需要实现功能:对一个文件的任意位置可以插入任何内容
@param filePath:文件路径
@param postion:追加内容添加位置
@param contents:追加内容
public static void addContentsToFile(String filePath, int postion, String contents) {

}

public static void addContainsToFile(String filePath,int position,String contents) throws IOException{
    //1、参数校验
        File file = new File(filePath);
        System.out.println(file);
        //判断文件是否存在
        if(!(file.exists() && file.isFile())){
            System.out.println("文件不存在  ~ ");
            return;
        }
        //判断position是否合法
        if((position < 0) || (position > file.length())){
            System.out.println("position不合法 ~ ");
            return;
        }

        //2、创建临时文件
        File tempFile =File.createTempFile("sss", ".temp",new File("d:/"));
        //File tempFile = new File("d:/wwwww.txt");
        //3、用文件输入流、文件输出流对文件进行操作
        FileOutputStream outputStream = new FileOutputStream(tempFile);
        FileInputStream inputStream = new FileInputStream(tempFile);
        //在退出JVM退出时自动删除
        tempFile.deleteOnExit();

        //4、创建RandomAccessFile流
        RandomAccessFile rw = new RandomAccessFile(file,"rw");
        //文件指定位置到 position
        rw.seek(position);

        int tmp;
        //5、将position位置后的内容写入临时文件
        while((tmp = rw.read())!=-1){
            outputStream.write(tmp);
        }
        //6、将追加内容 contents 写入 position 位置
        rw.seek(position);
        rw.write(contents.getBytes());

        //7、将临时文件写回文件,并将创建的流关闭
        while((tmp = inputStream.read())!=-1){
            rw.write(tmp);
        }
        rw.close();
        outputStream.close();
        inputStream.close();

测试:

String filePath = ("hehe.txt");
        //File file = new File("hehe.txt");
        String contents = new String("abc");
        try {
            addContainsToFile(filePath,3,contents);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

执行前:

这里写图片描述

执行后:

这里写图片描述

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以帮你解答这个问题。 首先,我们需要创建一个学生类,包含学生的基本信息,如姓名、学号、性别、年龄等。这里给出一个示例代码: ```java public class Student { private String name; private String id; private String gender; private int age; public Student(String name, String id, String gender, int age) { this.name = name; this.id = id; this.gender = gender; this.age = age; } // 省略 getter 和 setter 方法 public String toString() { return "姓名:" + name + "\n" + "学号:" + id + "\n" + "性别:" + gender + "\n" + "年龄:" + age + "\n"; } } ``` 接下来,我们需要实现从键盘上输入学生信息,并将学生信息保存在指定文本文件中的指定位置。这里我们可以使用 `BufferedWriter` 类来实现带缓存的写入操作。示例代码如下: ```java import java.io.*; public class StudentManager { private static final String FILE_PATH = "students.txt"; public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("请输入学生姓名:"); String name = br.readLine(); System.out.print("请输入学生学号:"); String id = br.readLine(); System.out.print("请输入学生性别:"); String gender = br.readLine(); System.out.print("请输入学生年龄:"); int age = Integer.parseInt(br.readLine()); Student student = new Student(name, id, gender, age); File file = new File(FILE_PATH); if (!file.exists()) { file.createNewFile(); } BufferedWriter bw = new BufferedWriter(new FileWriter(file, true)); bw.write(student.toString()); bw.close(); System.out.println("学生信息已保存。"); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意,在写入文件时需要指定 `FileWriter` 的第二个参数为 `true`,表示在文件末尾追加写入。 接下来,我们需要实现文本文件中读取特定学生信息。这里我们可以使用 `BufferedReader` 类来实现带缓存的读取操作。示例代码如下: ```java import java.io.*; public class StudentManager { private static final String FILE_PATH = "students.txt"; public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("请输入学生姓名:"); String name = br.readLine(); File file = new File(FILE_PATH); if (!file.exists()) { System.out.println("文件不存在。"); return; } BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { if (line.contains("姓名:" + name)) { System.out.println(line); break; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码中,我们通过读取文件中的每一行,查找包含指定学生姓名的行,并输出该行信息。 接下来,我们需要实现学生信息的增加、删除、修改、插入等操作。这里我们可以使用 `RandomAccessFile` 类来实现任意位置的读写操作。示例代码如下: ```java import java.io.*; public class StudentManager { private static final String FILE_PATH = "students.txt"; private static final int RECORD_SIZE = 100; public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("请选择操作(1-增加,2-删除,3-修改,4-插入):"); int choice = Integer.parseInt(br.readLine()); switch (choice) { case 1: addStudent(); break; case 2: deleteStudent(); break; case 3: updateStudent(); break; case 4: insertStudent(); break; default: System.out.println("无效操作。"); } } catch (IOException e) { e.printStackTrace(); } } private static void addStudent() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入学生姓名:"); String name = br.readLine(); System.out.print("请输入学生学号:"); String id = br.readLine(); System.out.print("请输入学生性别:"); String gender = br.readLine(); System.out.print("请输入学生年龄:"); int age = Integer.parseInt(br.readLine()); Student student = new Student(name, id, gender, age); RandomAccessFile raf = new RandomAccessFile(FILE_PATH, "rw"); raf.seek(raf.length()); raf.write(student.toString().getBytes()); raf.close(); System.out.println("学生信息已添加。"); } private static void deleteStudent() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入学生姓名:"); String name = br.readLine(); RandomAccessFile raf = new RandomAccessFile(FILE_PATH, "rw"); long pos = 0; String line; while ((line = raf.readLine()) != null) { if (line.contains("姓名:" + name)) { raf.seek(pos); raf.write(new byte[RECORD_SIZE]); break; } pos = raf.getFilePointer(); } raf.close(); System.out.println("学生信息已删除。"); } private static void updateStudent() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入学生姓名:"); String name = br.readLine(); RandomAccessFile raf = new RandomAccessFile(FILE_PATH, "rw"); String line; while ((line = raf.readLine()) != null) { if (line.contains("姓名:" + name)) { System.out.print("请输入学生学号:"); String id = br.readLine(); System.out.print("请输入学生性别:"); String gender = br.readLine(); System.out.print("请输入学生年龄:"); int age = Integer.parseInt(br.readLine()); Student student = new Student(name, id, gender, age); raf.seek(raf.getFilePointer() - RECORD_SIZE); raf.write(student.toString().getBytes()); break; } } raf.close(); System.out.println("学生信息已修改。"); } private static void insertStudent() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入插入位置(从0开始):"); int pos = Integer.parseInt(br.readLine()); System.out.print("请输入学生姓名:"); String name = br.readLine(); System.out.print("请输入学生学号:"); String id = br.readLine(); System.out.print("请输入学生性别:"); String gender = br.readLine(); System.out.print("请输入学生年龄:"); int age = Integer.parseInt(br.readLine()); Student student = new Student(name, id, gender, age); RandomAccessFile raf = new RandomAccessFile(FILE_PATH, "rw"); raf.seek(pos * RECORD_SIZE); byte[] buffer = new byte[(int) raf.length() - pos * RECORD_SIZE]; raf.read(buffer); raf.seek(pos * RECORD_SIZE); raf.write(student.toString().getBytes()); raf.write(buffer); raf.close(); System.out.println("学生信息已插入。"); } } ``` 上述代码中,我们通过 `RandomAccessFile` 类实现任意位置的读写操作,其中 `RECORD_SIZE` 定义了每个学生信息所占用的字节数。在删除学生信息时,我们使用了 `write(new byte[RECORD_SIZE])` 的方式来覆盖该学生信息所占用的字节。在插入学生信息时,我们先读取插入位置之后的内容,再将新的学生信息和读取的内容一起写入文件。 最后,需要注意的是,在读取文件时,我们需要使用与写入文件时相同的编码格式。在本例中,我们使用了默认的 UTF-8 编码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值