io学习(2)——创建文件并且读取、写入文件内容

实现创建一个txt文件并且读取内容,如果该文件存在则输出文件内容,如果不存在就创建文件,同时还可以写入内容

实现代码:

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

public class test {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文件要保存的位置");
        String path = scanner.nextLine();
        CreteAndRead(path);
        System.out.println("请输入要写入的内容");
        String str = scanner.nextLine();
        Write(path,str);
        }
        public static void CreteAndRead(String path) throws IOException {
            File file = new File(path);
            if(!file.exists()){
                System.out.println(file.createNewFile());
                System.out.println("文件创建成功");
            }else{
                try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
                    String line;
                    //读取读取文件内容并打印
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public static void Write(String path,String str) {
        try(FileWriter fr = new FileWriter(path)) {
            BufferedWriter bufw = new BufferedWriter(fr);
            bufw.write(str);
            bufw.flush();
            bufw.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("未找到文件");
        }
        }
}

先获取输入的位置,在判断该文章存在不存在该文件,如果存在,使用while方法逐个打印内容,如果不存在,新建该文件

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值