创建打开以及读写文件

创建文件

public static  void create()
{
    File file=new File("C:\\Users\\86186\\Desktop");
    if(!file.exists()){//如果文件夹不存在
        file.mkdir();//创建文件夹
    }
    try{//异常处理
        //如果文件夹下没有Li.txt就会创建该文件
        BufferedWriter bw=new BufferedWriter(new FileWriter("C:\\Users\\86186\\Desktop\\Li.txt"));
        bw.write("Hello I/O!");//在创建好的文件中写入"Hello I/O"
        bw.close();//一定要关闭文件
    }catch(IOException e){
        e.printStackTrace();
    }

}

打开文件夹的目录

//打开一个文件夹
public  static void open() {
    File file=new File("F:\\小工具包\\LO");
    String[] strs=file.list();
    for(String str:strs)
        System.out.println(str);

    File[] strss=file.listFiles();
    for(File str:strss)
        System.out.println(str);
}

读写文件

public static void fileRead() throws Exception {
        File file = new File("C:\\Users\\86186\\Desktop\\test.txt");//定义一个file对象,用来初始化FileReader
        FileReader reader = new FileReader(file);//定义一个fileReader对象,用来初始化BufferedReader
       // BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\86186\\Desktop\\test.txt"));
        BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象,将文件内容读取到缓存
        StringBuilder sb = new StringBuilder();//定义一个字符串缓存,将字符串存放缓存中
        String s = "";
        while ((s =bReader.readLine()) != null) {//逐行读取文件内容,不读取换行符和末尾的空格
            sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
            System.out.println(s);
        }
        bReader.close();
        String str = sb.toString();
        System.out.println(str );
        //return str;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值