io流实现对.txt文件的增删改查操作(文件中某一行内容的增加删除修改)

目录

一、要求

二、完整代码

三、结果演示

四、增删改查代码分析


一、要求

        我们需要利用io流对.txt文件中某行或者某几行内容进行增加、删除、修改操作,查看文件全部内容。

使用的类:

File

FileRead           --              BufferedReader

FileWriter          --              BufferedWriter

二、完整代码

Books:类

package com.nanchu;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @Author 南初
 * @Create 2024/2/29 8:44
 * @Version 1.0
 */
public class Books {
    private String bookName;
    private String bookPrice;
    private String bookNum;


    Scanner scan = new Scanner(System.in);
    // 添加图书
    public void addBook(File file) throws IOException {
        BufferedReader bufferedReader =  new BufferedReader(new FileReader(file));

        ArrayList<String> strb = new ArrayList<>();
        System.out.print("\n请输入图书名:");
        String name = scan.next();
        System.out.print("\n请输入图书价格:");
        String price = scan.next();
        System.out.print("\n请输入图书数量:");
        String num = scan.next();

        String addBook =name+","+price+","+num;
        String line =null;
        while((line = bufferedReader.readLine())!=null){
            strb.add(line);
        }
        strb.add(addBook);
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));;
        for(String info:strb){
            bw.write(info);
            bw.newLine();
        }
        // 关闭文件流
        bw.flush();
        bw.close();
        bufferedReader.close();
        System.out.println("添加图书成功!");
    }

    // delete 删除图书
    public void deleteBook(File file) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        ArrayList<String> strb = new ArrayList<>();
        System.out.println("请输入删除图书序号:");
        int bookID=scan.nextInt();  //修改图书序号
        String line = null;

        while((line = bufferedReader.readLine())!=null){
            strb.add(line);
        }
        int x = strb.size();
        while(true){
            if (bookID >= 0 &&bookID < x) {
                break;
            }else {
                System.out.println("输入错误,请重新输入删除图书序号:");
                bookID=scan.nextInt();  //修改图书序号
            }
        }
        System.out.println(strb.get(bookID));
        // 集合中删除图书
        strb.remove(bookID);
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for(String info :strb){
            bw.write(info);
            bw.newLine();
        }
        System.out.println("删除图书成功!");
        bw.flush();
        bw.close();
        bufferedReader.close();
    }

    // 修改图书
    public void alterBook(File file) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        ArrayList<String> strb = new ArrayList<>();
        String line = null;
        int count=0;

        System.out.print("请输入修改图书序号:");
        int bookID=scan.nextInt();  //修改图书序号

        while((line = bufferedReader.readLine())!=null){
            if(count == bookID){
                String[] strings = line.split(",");
                System.out.print("\n请输入图书名:");
                String name = scan.next();
                strings[0] = name;

                System.out.print("\n请输入图书价格:");
                String price = scan.next();
                strings[1] = price;

                System.out.print("\n请输入图书数量:");
                String num = scan.next();
                strings[2] = num;

                line =String.join(",", strings);
                strb.add(line);
                System.out.println("修改图书成功!");
            }else {
                strb.add(line);
            }
            count++;
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for(String info: strb){
            bw.write(info);
            bw.newLine();
        }
        bw.flush();
        bw.close();
        bufferedReader.close();
    }
    //  查看所有图书
    public void viewAllBook(File file) throws IOException {
        System.out.println("序号\t\t\t书名\t\t\t价格\t\t\t数量");
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String line = null;

        for(int i=0;(line=bufferedReader.readLine())!=null;i++){
            String[] strings = line.split(",");
            System.out.print(i +"\t\t\t");
            for(int j=0;j<strings.length;j++){
                System.out.print(strings[j]+"\t\t\t");
            }
            System.out.print("\n");
        }
        bufferedReader.close();
    }



}

ioFile类: 

package com.nanchu;

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

/**
 * @Author 南初
 * @Create 2024/2/29 8:36
 * @Version 1.0
 */
public class IoFile {
    public static void main(String[] args) {
        File file = new File("E:\\Java Code base\\FoodOrderingSystem\\src\\com\\nanchu\\test.txt");
        Books books = new Books();
        Scanner scan = new Scanner(System.in);
        while(true) {
            System.out.println("------请选择你的操作------");
            System.out.println("1.增   2.删   3.改   4.查   5.退出");
            System.out.print("请选择你需要的操作(这里默认输入除了1234之外的数字认为是退出):");
            int num = scan.nextInt();
            if (num == 1) {
                // 增
                try {
                    books.addBook(file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else if (num==2) {
                // 删
                try {
                    books.deleteBook(file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else if (num==3) {
                // 改
                try {
                    books.alterBook(file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else if (num==4) {
                // 查
                try {
                    books.viewAllBook(file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }else {
                break;
            }
        }
        System.out.println("运行结束!");

    }
}

test.txt

C,50.0,30
Java,40.0,50
Go,50.0,20

三、结果演示

增加操作:

 test.txt文件查看增加成功:

删除操作:

 test.txt文件查看删除成功:

修改数据操作:

  test.txt文件查看修改成功:

四、增删改查代码分析

增删改思想:

        1. 将  .txt  文件内容全部读取出来

        2. 创建ArrayList集合储存读取出来的内容

        3. 针对需要修改的某行或者或几行内容从ArrayList集合中取出进行增删改操作

        4. 创建BufferedWriter 对象 传入(new FileWriter(file)) ,而不是(new FileWriter(file,true)) 因为不需要将内容追加,增加true,意思是在原文件内容后面追加新内容,我们这里做的是将储存的内容写入到文件中,需要的是原文件的空白文件,不加true意思是覆盖已有的文件。

        5.  关闭流

        

对于输出流来说,File类的对象是可以不存在的。
   > 如果File类的对象不存在,则可以在输出的过程中,自动创建File类的对象
   > 如果File类的对象存在,
      > 如果调用FileWriter(File file)或FileWriter(File file,false),输出时会新建File文件覆盖已有的文件
      > 如果调用FileWriter(File file,true)构造器,则在现有的文件末尾追加写出内容。

增:

Scanner scan = new Scanner(System.in);
    // 添加图书
    public void addBook(File file) throws IOException {
        BufferedReader bufferedReader =  new BufferedReader(new FileReader(file));

        ArrayList<String> strb = new ArrayList<>();
        System.out.print("\n请输入图书名:");
        String name = scan.next();
        System.out.print("\n请输入图书价格:");
        String price = scan.next();
        System.out.print("\n请输入图书数量:");
        String num = scan.next();

        String addBook =name+","+price+","+num;
        String line =null;
        while((line = bufferedReader.readLine())!=null){
            strb.add(line);
        }
        strb.add(addBook);
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));;
        for(String info:strb){
            bw.write(info);
            bw.newLine();
        }
        // 关闭文件流
        bw.flush();
        bw.close();
        bufferedReader.close();
        System.out.println("添加图书成功!");
    }

删:

    Scanner scan = new Scanner(System.in);
 // delete 删除图书
    public void deleteBook(File file) throws IOException {

        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        ArrayList<String> strb = new ArrayList<>();
        System.out.println("请输入删除图书序号:");
        int bookID=scan.nextInt();  //修改图书序号
        String line = null;

        while((line = bufferedReader.readLine())!=null){
            strb.add(line);
        }
        int x = strb.size();
        while(true){
            if (bookID >= 0 &&bookID < x) {
                break;
            }else {
                System.out.println("输入错误,请重新输入删除图书序号:");
                bookID=scan.nextInt();  //修改图书序号
            }
        }
        System.out.println(strb.get(bookID));
        // 集合中删除图书
        strb.remove(bookID);
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for(String info :strb){
            bw.write(info);
            bw.newLine();
        }
        System.out.println("删除图书成功!");
        bw.flush();
        bw.close();
        bufferedReader.close();
    }

改:

Scanner scan = new Scanner(System.in);
// 修改图书
public void alterBook(File file) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

    ArrayList<String> strb = new ArrayList<>();
    String line = null;
    int count=0;

    System.out.print("请输入修改图书序号:");
    int bookID=scan.nextInt();  //修改图书序号

    while((line = bufferedReader.readLine())!=null){
        if(count == bookID){
            String[] strings = line.split(",");
            System.out.print("\n请输入图书名:");
            String name = scan.next();
            strings[0] = name;

            System.out.print("\n请输入图书价格:");
            String price = scan.next();
            strings[1] = price;

            System.out.print("\n请输入图书数量:");
            String num = scan.next();
            strings[2] = num;

            line =String.join(",", strings);
            strb.add(line);
            System.out.println("修改图书成功!");
        }else {
            strb.add(line);
        }
        count++;
    }
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    for(String info: strb){
        bw.write(info);
        bw.newLine();
    }
    bw.flush();
    bw.close();
    bufferedReader.close();
}

查:

Scanner scan = new Scanner(System.in);
//  查看所有图书
public void viewAllBook(File file) throws IOException {
    System.out.println("序号\t\t\t书名\t\t\t价格\t\t\t数量");
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
    String line = null;

    for(int i=0;(line=bufferedReader.readLine())!=null;i++){
        String[] strings = line.split(",");
        System.out.print(i +"\t\t\t");
        for(int j=0;j<strings.length;j++){
            System.out.print(strings[j]+"\t\t\t");
        }
        System.out.print("\n");
    }
    bufferedReader.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值