2022-08-09 利用IO流写一个简单的商店商品的增删改查

目录

Goods类:

ShopTwo类:

增加商品:

删除商品:

查找一个:

修改:

操作类


首先定义一个存储商店商品编号/商品名称/商品价格的类:

并重写toString方法为了方便查看。

Goods类:

public class Goods {
    private Integer id;//商品编号
    private String name;//商品名称
    private Integer price;//商品价格
    public Goods(){}

    public Goods(Integer id, String name, Integer price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

写增删改查的方法:

ShopTwo类:

首先建一个缓冲流输入输出流对象和一个集合,集合是为了方便实现删除等操作,起到一个中间文件的作用,因为IO流没有删除更改等操作,所以需要把文本文件转换成一个集合方便操作:

public class ShopTwo {
    private static BufferedReader bufferedReader =null;
    private static BufferedWriter bufferedWriter =null;
    private static List<Goods> list;
}

增加商品:

public static void insert(Scanner sc){
        System.out.println("请输入商品编号:");
        Integer id=sc.nextInt();
        System.out.println("请输入商品名称");
        String name = sc.next();
        System.out.println("请输入商品价格");
        Integer price= sc.nextInt();
        try {
            bufferedWriter = new BufferedWriter(new                 FileWriter("c:/summerjava/d.txt",true));
            String read=id+" "+name+" "+price;
            bufferedWriter.write("\n"+read);//换行添加
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            IOUtil.closeIO(null,bufferedWriter);
        }
        //直接追加:
    }

 我先封装了一个方法addList(),因为他们都需要先把文件的内容添加到集合里:

public static void addList(){
        try {
            list = new ArrayList<>();
            bufferedReader = new BufferedReader(new FileReader("c:/summerjava/d.txt"));
            String read;
            while((read=bufferedReader.readLine())!=null){
                String[] s =read.split(" ");//把文本文档的内容以空格为界分为数组存储到s里
                Goods goods = new Goods(Integer.valueOf(s[0]),s[1],Integer.valueOf(s[2]));
                //利用构造器存到对象中,然后添加到集合中
                list.add(goods);
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            IOUtil.closeIO(bufferedReader,null);
        }
    }

删除商品:

public static void delete(Scanner sc){
        System.out.println("请输入商品编号:");
        //全部拿出来,删除后覆盖
        int id = sc.nextInt();
        try {
            addList();
            bufferedWriter = new BufferedWriter(new FileWriter("c:/summerjava/d.txt"));
            Iterator<Goods> iterator = list.iterator();
            while(iterator.hasNext()){//利用迭代器循环判断删除传入id的商品
                Goods goods=iterator.next();
                if(id==goods.getId()){
                    iterator.remove();
                }
            }
            for (Goods goods: list) {//把删除后的集合写入
                bufferedWriter.write(goods.getId()+" "+goods.getName()+" "+ goods.getPrice());
                bufferedWriter.newLine();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            IOUtil.closeIO(null,bufferedWriter);
        }
    }

查找一个:

public static void findOne(Scanner sc){
        System.out.println("请输入商品编号:");
        int id = sc.nextInt();
        ShopTwo.addList();//把文件读取到集合里;
        for (Goods goods: list) {
            if(id==goods.getId()){
                System.out.println(goods);//查找到并输出
            }
        }
    }

修改:

public static void update(Scanner sc){
        //全部拿出来,放集合里,然后改。更新后覆盖
        System.out.println("请输入商品编号:");
        //全部拿出来,删除后覆盖
        int id = sc.nextInt();
        try {
            addList();
            bufferedWriter = new BufferedWriter(new FileWriter("c:/summerjava/d.txt"));
            Iterator<Goods> iterator = list.iterator();
            while(iterator.hasNext()){
                Goods goods=iterator.next();
                if(id==goods.getId()){
                    System.out.println("请输入您要修改后的商品名称");
                    goods.setName(sc.next());
                    System.out.println("请输入您要修改后的商品价格");
                    goods.setPrice(sc.nextInt());
                }
            }
            for (Goods goods: list) {
                bufferedWriter.write(goods.getId()+" "+goods.getName()+" "+ goods.getPrice());
                bufferedWriter.newLine();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            IOUtil.closeIO(null,bufferedWriter);
        }
    }

操作类

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.println("请选择功能:1.插入新商品、2.删除商品、3.修改商品、4.查找一个商品、5.退出");
            String flag = sc.next();
            switch (flag) {
                case "1":
                    ShopTwo.insert(sc);
                    break;
                case "2":
                    ShopTwo.delete(sc);
                    break;
                case "3":
                    ShopTwo.update(sc);
                    break;
                case "4":
                    ShopTwo.findOne(sc);
                    break;
                case "5":
                    System.out.println("退出成功");
                    System.exit(-1);
                    break;
                default:
                    break;
            }
        }
    }
}

运行效果:

 增加:

查看: 

 

删除: 

 

修改: 

 

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Boot可以快速搭建一个基于RESTful API的用户增删改查功能。 首先,需要新建一个Spring Boot项目,可以通过Spring Initializr(https://start.spring.io/)进行初始化。 接下来,通过引入相关的依赖,创建用户实体类和数据库访问接口。 1. 创建用户实体类 ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // 省略构造方法、getter和setter } ``` 2. 创建数据库访问接口 ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 3. 创建用户控制器类 ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/") public List<User> getAllUsers() { return userRepository.findAll(); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id)); } @PostMapping("/") public User createUser(@RequestBody User user) { return userRepository.save(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User userDetails) { User user = userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id)); user.setName(userDetails.getName()); user.setEmail(userDetails.getEmail()); return userRepository.save(user); } @DeleteMapping("/{id}") public ResponseEntity<?> deleteUser(@PathVariable Long id) { User user = userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id)); userRepository.delete(user); return ResponseEntity.ok().build(); } } ``` 以上代码中,`@RestController`注解表示这是一个RESTful API控制器类,`@RequestMapping("/users")`指定了API的基础路径为"/users"。 4. 配置数据库连接 在`application.properties`文件中配置数据库连接相关信息,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.jpa.hibernate.ddl-auto=create ``` 这里假设使用MySQL数据库,数据库名为"mydatabase",用户名为"root",密码为"123456"。 5. 运行应用程序 通过运行Spring Boot应用程序,应用程序将监听在默认端口(通常是8080)。可以使用Postman或其他HTTP客户端工具发送HTTP请求来测试API。 通过发送GET请求到`http://localhost:8080/users/`,可以获取所有用户的列表。 通过发送GET请求到`http://localhost:8080/users/{id}`,可以获取指定ID的用户信息。 通过发送POST请求到`http://localhost:8080/users/`,可以创建一个新用户。 通过发送PUT请求到`http://localhost:8080/users/{id}`,可以更新指定ID的用户信息。 通过发送DELETE请求到`http://localhost:8080/users/{id}`,可以删除指定ID的用户。 以上就是使用Spring Boot快速搭建用户增删改查功能的基本步骤。当然,还可以根据实际需求进行更多的定制和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值