向指定文件夹创建文件,并且写入信息

java 复制代码
    public static void main(String[] args) throws IOException {
        String filePath = "E:\\mytemp";
        File file = new File(filePath);
        String filePath2 = "E:\\mytemp\\hello.txt";
        File file1 = new File(filePath2);
        if (!(file.exists() && file.isDirectory() && file1.exists())) {
            System.out.println("目录不存在,正在创建...");
            file.mkdir();
        } else {
            System.out.println("该文件已经存在,就不要再重复创建了");
        }
        //以下代码正在写入文本内容
        {
            System.out.println("文件、目录已存在,正在输入文本~");
            String context = "hehdhdfh~";
            BufferedWriter bw = new BufferedWriter(new FileWriter(filePath2));
            bw.write(context);
            bw.close();
        }
    }
java 复制代码
public class Homework01 {
    public static void main(String[] args) throws IOException {
        String filePath = "E:\\mytemp";
        File file = new File(filePath);
        if(!file.exists()){
            if(file.mkdir()){
                System.out.println("目录创建成功");
            }else {
                System.out.println("创建目录失败");
            }
        }
        String filePath2 = filePath+"\\hello.txt";
        file = new File(filePath2);
        if(!file.exists()){
            //创建文件
            if(file.createNewFile()){
                System.out.println(filePath2+"文件创建成功~");
            }else{
                System.out.println(filePath2+"文件创建失败~");
            }
        }else{
            System.out.println(filePath2+"文件已经存在,无需继续创建~");
        }
        //以下代码正在写入文本内容
        {
            System.out.println("正在输入文本~");
            String context = "hello,worldl!~";
            BufferedWriter bw = new BufferedWriter(new FileWriter(filePath2));
            bw.write(context);
            System.out.println("文本输入成功!");
            bw.close();
        }
    }
}
相关推荐
CarIise1 小时前
Spring MVC 请求参数绑定与常用注解
java·spring·mvc
码途行者1 小时前
处理超时未支付订单:两套轻量化方案,附 PHP 极简实现
开发语言·redis·php
云和数据.ChenGuang1 小时前
LangChain 实战指南:从入门到构建智能应用
开发语言·人工智能·python·langchain
IT_陈寒1 小时前
Vite性能优化完全指南
前端·人工智能·后端
const_qiu1 小时前
第三章 04:3.6 基础调用链的构建
开发语言·python
燕落南枝1 小时前
HTML 表单入门:表单容器、文本框与密码框属性详解
前端·microsoft·html
一条泥憨鱼1 小时前
AI Agent 安全实践:从 MCP 工具调用到 Java 权限校验
java·人工智能·安全
向上的车轮1 小时前
Python 大数据处理不慢:Polars + DuckDB + Arrow 实战指南
开发语言·python
Nebula_g1 小时前
云禾外卖补充—项目整体后端运行逻辑-对流程的更深层次理解
java·开发语言·网络·数据库·状态模式·javase
萧瑟余晖1 小时前
Spring Security 6.x新特性与架构演进详解
java·spring·架构