当前位置: 首页 > news >正文

6-Java中新建一个文件、目录、路径

文章目录

  • 前言
  • 1-文件、目录、路径
  • 2-在当前路径下创建一个文件
  • 3-在当前路径下创建一个文件夹(目录)
    • 3.1 测试1-路径已经存在
    • 3.2 测试2-路径不存在
    • 3.2 创建不存在的路径并新建文件
    • 3.3 删除已存在的文件并新建
  • 4-总结

前言

学习Java中如何新建文件、目录、路径

1-文件、目录、路径

文件fileName,就如我们在电脑中看到的.txt、.java、.doc等
目录dir,可以理解成文件夹,里面可以包含多个文件夹或文件
路径directoryPath,有绝对路径和相对路径,这个不需要多说,但需要注意的是,如果想把win11电脑上已经存在的路径用来创建File实例,需要注意加转义符

2-在当前路径下创建一个文件

Main.java

class MainActivity{public static void main(String[] args){System.out.println("Main thread is running...");FileTest1.createAFileInCurrentPath("DefaultJavaFile1.java", null);}
}

FileTest1.java

import java.io.*;class FileTest1{// the path of the fileNameString directoryPath;// the name of the fileNameString fileName;FileTest1(){}FileTest1(String directoryPath, String fileName){this.directoryPath = directoryPath;this.fileName = fileName;}static void createAFileInCurrentPath(String fileName, String directoryPath){if (null == directoryPath){directoryPath = ".";}File tempFile = new File(directoryPath, fileName);try{tempFile.createNewFile();}catch (IOException e){System.out.println("文件创建异常!");}}}

上面的代码中,如果createAFileInCurrentPath方法传入的directoryPath为"."也是可以的,就表示当前路径

3-在当前路径下创建一个文件夹(目录)

3.1 测试1-路径已经存在

Main.java

import java.io.*;class MainActivity{public static void main(String[] args){System.out.println("Main thread is running...");String existedPath1 = "D:\\JavaAndroidLearnningDiary\\《Java 2实用教程》(5版 耿祥义、张跃平)\\Chapter10\\Leson1";String testFileName1 = "实习日志.java";//create a file in current pathFileTest1.createAFileInCurrentPath("DefaultJavaFile1.java", ".");//create a file in certain pathFile testFile1 = new File(existedPath1, testFileName1);FileTest1.createAFileInCertainPath(testFile1);}
}

FileTest1.java

import java.io.*;class FileTest1{// the path of the fileNameString directoryPath;// the name of the fileNameString fileName;FileTest1(){}FileTest1(String directoryPath, String fileName){this.directoryPath = directoryPath;this.fileName = fileName;}static void createAFileInCurrentPath(String fileName, String directoryPath){if (null == directoryPath){directoryPath = ".";}File tempFile = new File(directoryPath, fileName);try{tempFile.createNewFile();}catch (IOException e){System.out.println("文件创建异常!");}}static void createAFileInCertainPath(File file){try{file.createNewFile();}catch(Exception e){System.out.println(e);}}}

测试结果:编译通过、解释运行正常,创建了新文件

3.2 测试2-路径不存在

Main.java

import java.io.*;class MainActivity{public static void main(String[] args){System.out.println("Main thread is running...");String existedPath1 = "D:\\JavaAndroidLearnningDiary\\《Java 2实用教程》(5版 耿祥义、张跃平)\\Chapter10\\Leson1\\Lesson1~4_Review1";String testFileName1 = "实习日志.java";String unExistedPath1 = "D:\\JavaAndroidLearnningDiary\\《Java 2实用教程》(5版 耿祥义、张跃平)\\Chapter10\\Leson1\\Lesson1~4_Review1\\testDir1";String testFileName2 = "学习笔记.java";//create a file in current pathFileTest1.createAFileInCurrentPath("DefaultJavaFile1.java", ".");//create a file in certain and existed pathFile testFile1 = new File(existedPath1, testFileName1);FileTest1.createAFileInCertainPath(testFile1);//create a file in certain but not existed pathFile testFile2 = new File(unExistedPath1, testFileName2);FileTest1.createAFileInCertainPath(testFile2);}
}

FileTest1.java

import java.io.*;class FileTest1{// the path of the fileNameString directoryPath;// the name of the fileNameString fileName;FileTest1(){}FileTest1(String directoryPath, String fileName){this.directoryPath = directoryPath;this.fileName = fileName;}static void createAFileInCurrentPath(String fileName, String directoryPath){if (null == directoryPath){directoryPath = ".";}File tempFile = new File(directoryPath, fileName);try{tempFile.createNewFile();}catch (IOException e){System.out.println("文件创建异常!");}}static void createAFileInCertainPath(File file){try{file.createNewFile();}catch(Exception e){System.out.println(e);}}}

测试结果如下
在这里插入图片描述

3.2 创建不存在的路径并新建文件

Main.java

import java.io.*;class MainActivity{public static void main(String[] args){System.out.println("Main thread is running...");String existedPath1 = "D:\\JavaAndroidLearnningDiary\\《Java 2实用教程》(5版 耿祥义、张跃平)\\Chapter10\\Leson1\\Lesson1~4_Review1";String testFileName1 = "实习日志.java";String unExistedPath1 = "D:\\JavaAndroidLearnningDiary\\《Java 2实用教程》(5版 耿祥义、张跃平)\\Chapter10\\Leson1\\Lesson1~4_Review1\\testDir1";String testFileName2 = "学习笔记.java";//create a file in current pathFileTest1.createAFileInCurrentPath("DefaultJavaFile1.java", ".");//create a file in certain and existed pathFile testFile1 = new File(existedPath1);FileTest1.createAFileInCertainPath(testFile1);//create a file in certain but not existed pathFileTest1.createAFileInCertainPath(testFileName2, unExistedPath1);}
}

FileTest1.java

import java.io.*;class FileTest1{// the path of the fileNameString directoryPath;// the name of the fileNameString fileName;FileTest1(){}FileTest1(String directoryPath, String fileName){this.directoryPath = directoryPath;this.fileName = fileName;}static void createAFileInCurrentPath(String fileName, String directoryPath){if (null == directoryPath){directoryPath = ".";}File tempFile = new File(directoryPath, fileName);try{tempFile.createNewFile();}catch (IOException e){System.out.println("文件创建异常!");}}static void createAFileInCertainPath(File file){try{if (file.exists()){file.createNewFile();}else{System.out.println("the path is not existed ! here are the information of the path:");System.out.println("Name :"+file.getName());System.out.println("AbsoluteFile :"+file.getAbsoluteFile());System.out.println("AbsolutePath :"+file.getAbsolutePath());}}catch(Exception e){System.out.println(e);}}static void createAFileInCertainPath(String fileName, String directoryPath){File tempFileName, tempDirectoryPath;if (null != directoryPath){tempDirectoryPath = new File(directoryPath);System.out.println("Is tempFileName a directory :"+tempDirectoryPath.isDirectory());tempDirectoryPath.mkdirs();}if (null != fileName){tempFileName = new File(directoryPath, fileName);System.out.println("Is tempFileName a file :"+tempFileName.isFile());try{tempFileName.createNewFile();}catch(Exception e){System.out.println("在未存在的路径下创建文件失败!");}}}}

测试结果:编译通过、解释运行,创建成功

3.3 删除已存在的文件并新建

Main.java

import java.io.*;class MainActivity{public static void main(String[] args){System.out.println("Main thread is running...");String existedPath1 = "D:\\JavaAndroidLearnningDiary\\《Java 2实用教程》(5版 耿祥义、张跃平)\\Chapter10\\Leson1\\Lesson1~4_Review1";String testFileName1 = "实习日志.java";String unExistedPath1 = "D:\\JavaAndroidLearnningDiary\\《Java 2实用教程》(5版 耿祥义、张跃平)\\Chapter10\\Leson1\\Lesson1~4_Review1\\testDir2";String testFileName2 = "学习笔记.java";//create a file in current path//create a file in certain and existed pathFile testFile1 = new File(existedPath1);FileTest1.createAFileInCertainPath(testFile1);//create a file in certain but not existed pathFileTest1.createAFileInCertainPath(testFileName2, unExistedPath1);//delete a file in current pathFileTest1.deleteAFileInCurrentPath("DefaultJavaFile1.java");//delete a file in certain pathString deleteTestPath1 = "D:\\TestPath1\\TestDir1\\TestDir2\\TestDir3\\TestDir3_1\\测试.txt";FileTest1.deleteAFileInCeratainPath("D:\\TestPath1\\TestDir1\\TestDir2\\TestDir3\\TestDir3_1", "测试.txt");//delete a dir in certain pathFileTest1.deleteADirInCertainPath("D:\\TestPath1\\TestDir1\\TestDir2\\TestDir3\\TestDir3_2");}
}

FileTest1.java

import java.io.*;class FileTest1{// the path of the fileNameString directoryPath;// the name of the fileNameString fileName;FileTest1(){}FileTest1(String directoryPath, String fileName){this.directoryPath = directoryPath;this.fileName = fileName;}static void createAFileInCurrentPath(String fileName, String directoryPath){if (null == directoryPath){directoryPath = ".";}File tempFile = new File(directoryPath, fileName);try{tempFile.createNewFile();}catch (IOException e){System.out.println("文件创建异常!");}}static void createAFileInCertainPath(File file){try{if (!file.exists()){file.createNewFile();}else{}}catch(Exception e){System.out.println(e);}}static void createAFileInCertainPath(String fileName, String directoryPath){File tempFileName, tempDirectoryPath;if (null != directoryPath){tempDirectoryPath = new File(directoryPath);System.out.println("Is tempFileName a directory :"+tempDirectoryPath.isDirectory());tempDirectoryPath.mkdirs();}if (null != fileName){tempFileName = new File(directoryPath, fileName);System.out.println("Is tempFileName a file :"+tempFileName.isFile());try{tempFileName.createNewFile();}catch(Exception e){System.out.println("在未存在的路径下创建文件失败!");}}}static void deleteAFileInCurrentPath(String fileName){System.out.println("Function deleteAFileInCurrentPath is running---------");File tempFile = new File(fileName);try{if (tempFile.exists()){System.out.println(tempFile.getName()+" 文件存在");tempFile.delete();}else{System.out.println("文件不存在");}}catch(Exception e){System.out.println("删除文件失败!");}System.out.println("Function deleteAFileInCurrentPath is finished---------");}static void deleteAFileInCeratainPath(String directory, String fileName){System.out.println("Function deleteAFileInCeratainPath is running---------");File tempFile = new File(directory, fileName);try{if (tempFile.exists()){System.out.println(tempFile.getName()+" 文件存在");tempFile.delete();}else{System.out.println("文件不存在");}}catch(Exception e){System.out.println("删除文件失败!");}System.out.println("Function deleteAFileInCeratainPath is finished---------");}static void deleteADirInCertainPath(String directory){System.out.println("Function deleteADirInCertainPath is running---------");File tempFile = new File(directory);try{if (tempFile.exists()){System.out.println(tempFile.getName()+" 文件存在");tempFile.delete();}else{System.out.println("文件不存在");}}catch(Exception e){System.out.println("删除文件失败!");}System.out.println("Function deleteADirInCertainPath is finished---------");}}

4-总结

1.简要学习了Java中如何创建文件、目录
2.在调试过程中遇到了一些问题
(1)导包,本来想使用Nullable,但似乎没有相关包
(2)直接在java文件的目录下打开的Windows power Shell窗口中运行时,显示无法加载主类MainActivity,而打开的cmd窗口却可以运行
(3)如果实例化的File对象中的路径是磁盘里不存在的,则isFile、isDirectory全返回false

相关文章:

6-Java中新建一个文件、目录、路径

文章目录前言1-文件、目录、路径2-在当前路径下创建一个文件3-在当前路径下创建一个文件夹(目录)3.1 测试1-路径已经存在3.2 测试2-路径不存在3.2 创建不存在的路径并新建文件3.3 删除已存在的文件并新建4-总结前言 学习Java中如何新建文件、目录、路径…...

Bootstrap系列之Flex布局

文章目录Bootstrap中的Flexd-flex与d-inline-flex也存在响应式变化flex水平布局flex垂直布局flex水平与垂直也存在响应式变化内容排列(justify-content响应式变化也存在于这里sm,md,lg,xl)子元素对齐方式Align items&a…...

匈牙利算法与KM算法的区别

前记 在学习过程中,发现很多博客将匈牙利算法和KM算法混为一谈,当时只管用不管分析区别,所以现在来分析一下两个算法之间的区别。 匈牙利算法在二分图匹配的求解过程中共两个原则: 1.最大匹配数原则 2.先到先得原则 而KM算法求…...

You Only Need 90K Parameters to Adapt Light 论文阅读笔记

这是BMVC2022的论文,提出了一个轻量化的局部全局双支路的低光照图像质量增强网络,有监督。 思路是先用encoder f(⋅)f(\cdot)f(⋅)转到raw-RGB域,再用decoder gt(⋅)g_t(\cdot)gt​(⋅)模拟ISP过程转到sRGB域。虽然文章好像没有明确指出&…...

【vue2小知识】实现axios的二次封装

🥳博 主:初映CY的前说(前端领域) 🌞个人信条:想要变成得到,中间还有做到! 🤘本文核心:在vue2中实现axios的二次封装 目录 一、平常axios的请求发送方式 二、axios的一次封装…...

走近php的数组:数组的定义与数组函数

数组是一种数据结构,它由一组元素组成,这些元素可以是相同类型或不同类型。数组是在程序运行时动态创建的,可以根据需要增加或删除元素,因此它们是非常灵活和实用的数据结构。在大多数编程语言中,数组都有一个索引&…...

Docker 应用实践-仓库篇

目前 Docker 官方维护了一个公共仓库 Docker Hub,用于查找和与团队共享容器镜像,界上最大的容器镜像存储库,拥有一系列内容源,包括容器社区开发人员、开放源代码项目和独立软件供应商(ISV)在容器中构建和分…...

python+django篮球NBA周边商城vue

目 录 第一章 绪 论 1 1.1背景及意义 1 1.2国内外研究概况 1 1.3 研究的内容 1 第二章 关键技术的研究 3 2.1 vue技术介绍 3 myproject/ <-- 高级别的文件夹 |-- myproject/ <-- Django项目文件夹 | |-- myproje…...

抽象类与接口的区别

抽象类什么是抽象类&#xff1f;抽象类是特殊的类&#xff0c;只是不能被实例化&#xff1b;除此以外&#xff0c;具有类的其他特性&#xff1b;重要的是抽象类可以包括抽象方法&#xff0c;这是普通类所不能的。抽象方法只能声明于抽象类中&#xff0c;且不包含任何实现&#…...

1904. 你完成的完整对局数

题目&#xff1a; 一款新的在线电子游戏在近期发布&#xff0c;在该电子游戏中&#xff0c;以 刻钟 为周期规划若干时长为 15 分钟 的游戏对局。这意味着&#xff0c;在 HH:00、HH:15、HH:30 和 HH:45 &#xff0c;将会开始一个新的对局&#xff0c;其中 HH 用一个从 00 到 23…...

Vue3:自定义指令以及简单的后台管理权限封装

目录 前言&#xff1a; 自定义指令介绍&#xff1a; 局部的自定义指令&#xff1a; 全局自定义指令&#xff1a; 讲讲后台管理权限管理&#xff1a; 前言&#xff1a; 说起这个自定义指令的使用场景&#xff0c;我第一反应就是&#xff0c;后台管理的权限管理&#xff0c;要…...

剑指 Offer 12. 矩阵中的路径

摘要 剑指 Offer 12. 矩阵中的路径 一、回溯算法解析 本问题是典型的矩阵搜索问题&#xff0c;可使用 深度优先搜索&#xff08;DFS&#xff09; 剪枝解决。 深度优先搜索&#xff1a; 可以理解为暴力法遍历矩阵中所有字符串可能性。DFS 通过递归&#xff0c;先朝一个方向搜…...

springboot+jersey+tomcat实现跨域方式上传文件到服务器

前言 在服务器上&#xff0c;当我们启动了tomcat&#xff0c;就可以以 http://ip地址:8080/文件路径/文件名 的方式&#xff0c;进行访问到我们服务器上处于tomcat的webapps文件夹下的文件 于是为了可以往上面加文件&#xff0c;我们有两种方式&#xff0c;一种就是直接复制文…...

【微信小程序】-- 常用视图容器类组件介绍 -- view、scroll-view和swiper(六)

&#x1f48c; 所属专栏&#xff1a;【微信小程序开发教程】 &#x1f600; 作  者&#xff1a;我是夜阑的狗&#x1f436; &#x1f680; 个人简介&#xff1a;一个正在努力学技术的CV工程师&#xff0c;专注基础和实战分享 &#xff0c;欢迎咨询&#xff01; &#…...

猜数字游戏——C++

我们在有了一定的C基础了以后&#xff0c;简单的实现一个案例&#xff08;其实只要会while循环结构就行了&#xff09;&#xff0c;我们本章内容会实现猜数字游戏&#xff0c;大家有什么语法疑问可以看看我写的&#xff1a;C快速入门_染柒_GRQ的博客-CSDN博客&#xff0c;该博客…...

整数对最小和

题目描述 给定两个整数数组 array1 array2。数组元素按升序排列&#xff0c;假设从array1 、array2中分别取出一个元素可构成一对元素&#xff0c;现在需要取出K个元素并对取出的所有元素求和&#xff0c;计算和的最小值 注意事项 两对元素如果对应于array1 array2中的两个下…...

2023-2-22 -javaagent

周三&#xff0c;天气晴&#xff0c;7度 Java Agent Java Agent也叫作java探针&#xff0c;可以实现动态修改java字节码&#xff0c;完成额外的功能。在java类编译成字节码&#xff0c;在jvm执行之前&#xff0c;它可以读取修改字节码&#xff0c;以来完成额外的功能。 使用…...

JavaScript BOM操作

目录 前言 window 对象 location 对象 navigator 对象 screen 对象 history 对象 前言 BOM&#xff08;Browser Object Model&#xff09;指的是浏览器对象模型&#xff0c;它是 JavaScript 和浏览器之间的接口。通过 BOM&#xff0c;JavaScript 可以与浏览器窗口交互&…...

【机器学习 | 强基计划】开山篇 | 机器学习介绍及其类别和概念阐述

🤵‍♂️ 个人主页: @计算机魔术师 👨‍💻 作者简介:CSDN内容合伙人,全栈领域优质创作者。 机器学习 | 强基计划系列 (一) 作者: 计算机魔术师 版本: 1.0 ( 2022.2.25) 注释:文章会不定时更新补充 文章目录 前言一、机器学习概览1.1 有监督学习和无监督学习1.1.…...

华为OD机试真题Java实现【合规数组】真题+解题思路+代码(20222023)

合规数组 题目 给定一个正整数数组 检查数组中是否存在满足规则的数组组合 规则: A = B + 2C 🔥🔥🔥🔥🔥👉👉👉👉👉👉 华为OD机试(Java)真题目录汇总 ## 输入 第一行输出数组的元素个数 接下来一行输出所有数组元素,用空格隔开 输出 如果存在满…...

Python爬虫实战:研究MechanicalSoup库相关技术

一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...

无法与IP建立连接,未能下载VSCode服务器

如题&#xff0c;在远程连接服务器的时候突然遇到了这个提示。 查阅了一圈&#xff0c;发现是VSCode版本自动更新惹的祸&#xff01;&#xff01;&#xff01; 在VSCode的帮助->关于这里发现前几天VSCode自动更新了&#xff0c;我的版本号变成了1.100.3 才导致了远程连接出…...

五年级数学知识边界总结思考-下册

目录 一、背景二、过程1.观察物体小学五年级下册“观察物体”知识点详解&#xff1a;由来、作用与意义**一、知识点核心内容****二、知识点的由来&#xff1a;从生活实践到数学抽象****三、知识的作用&#xff1a;解决实际问题的工具****四、学习的意义&#xff1a;培养核心素养…...

Python爬虫(一):爬虫伪装

一、网站防爬机制概述 在当今互联网环境中&#xff0c;具有一定规模或盈利性质的网站几乎都实施了各种防爬措施。这些措施主要分为两大类&#xff1a; 身份验证机制&#xff1a;直接将未经授权的爬虫阻挡在外反爬技术体系&#xff1a;通过各种技术手段增加爬虫获取数据的难度…...

蓝桥杯3498 01串的熵

问题描述 对于一个长度为 23333333的 01 串, 如果其信息熵为 11625907.5798&#xff0c; 且 0 出现次数比 1 少, 那么这个 01 串中 0 出现了多少次? #include<iostream> #include<cmath> using namespace std;int n 23333333;int main() {//枚举 0 出现的次数//因…...

【学习笔记】erase 删除顺序迭代器后迭代器失效的解决方案

目录 使用 erase 返回值继续迭代使用索引进行遍历 我们知道类似 vector 的顺序迭代器被删除后&#xff0c;迭代器会失效&#xff0c;因为顺序迭代器在内存中是连续存储的&#xff0c;元素删除后&#xff0c;后续元素会前移。 但一些场景中&#xff0c;我们又需要在执行删除操作…...

Ubuntu Cursor升级成v1.0

0. 当前版本低 使用当前 Cursor v0.50时 GitHub Copilot Chat 打不开&#xff0c;快捷键也不好用&#xff0c;当看到 Cursor 升级后&#xff0c;还是蛮高兴的 1. 下载 Cursor 下载地址&#xff1a;https://www.cursor.com/cn/downloads 点击下载 Linux (x64) &#xff0c;…...

深度学习之模型压缩三驾马车:模型剪枝、模型量化、知识蒸馏

一、引言 在深度学习中&#xff0c;我们训练出的神经网络往往非常庞大&#xff08;比如像 ResNet、YOLOv8、Vision Transformer&#xff09;&#xff0c;虽然精度很高&#xff0c;但“太重”了&#xff0c;运行起来很慢&#xff0c;占用内存大&#xff0c;不适合部署到手机、摄…...

【Veristand】Veristand环境安装教程-Linux RT / Windows

首先声明&#xff0c;此教程是针对Simulink编译模型并导入Veristand中编写的&#xff0c;同时需要注意的是老用户编译可能用的是Veristand Model Framework&#xff0c;那个是历史版本&#xff0c;且NI不会再维护&#xff0c;新版本编译支持为VeriStand Model Generation Suppo…...

客户案例 | 短视频点播企业海外视频加速与成本优化:MediaPackage+Cloudfront 技术重构实践

01技术背景与业务挑战 某短视频点播企业深耕国内用户市场&#xff0c;但其后台应用系统部署于东南亚印尼 IDC 机房。 随着业务规模扩大&#xff0c;传统架构已较难满足当前企业发展的需求&#xff0c;企业面临着三重挑战&#xff1a; ① 业务&#xff1a;国内用户访问海外服…...