当前位置: 首页 > 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)真题目录汇总 ## 输入 第一行输出数组的元素个数 接下来一行输出所有数组元素,用空格隔开 输出 如果存在满…...

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…...

Zustand 状态管理库:极简而强大的解决方案

Zustand 是一个轻量级、快速和可扩展的状态管理库&#xff0c;特别适合 React 应用。它以简洁的 API 和高效的性能解决了 Redux 等状态管理方案中的繁琐问题。 核心优势对比 基本使用指南 1. 创建 Store // store.js import create from zustandconst useStore create((set)…...

华为OD机试-食堂供餐-二分法

import java.util.Arrays; import java.util.Scanner;public class DemoTest3 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint a in.nextIn…...

sqlserver 根据指定字符 解析拼接字符串

DECLARE LotNo NVARCHAR(50)A,B,C DECLARE xml XML ( SELECT <x> REPLACE(LotNo, ,, </x><x>) </x> ) DECLARE ErrorCode NVARCHAR(50) -- 提取 XML 中的值 SELECT value x.value(., VARCHAR(MAX))…...

GruntJS-前端自动化任务运行器从入门到实战

Grunt 完全指南&#xff1a;从入门到实战 一、Grunt 是什么&#xff1f; Grunt是一个基于 Node.js 的前端自动化任务运行器&#xff0c;主要用于自动化执行项目开发中重复性高的任务&#xff0c;例如文件压缩、代码编译、语法检查、单元测试、文件合并等。通过配置简洁的任务…...

Git 3天2K星标:Datawhale 的 Happy-LLM 项目介绍(附教程)

引言 在人工智能飞速发展的今天&#xff0c;大语言模型&#xff08;Large Language Models, LLMs&#xff09;已成为技术领域的焦点。从智能写作到代码生成&#xff0c;LLM 的应用场景不断扩展&#xff0c;深刻改变了我们的工作和生活方式。然而&#xff0c;理解这些模型的内部…...

WebRTC从入门到实践 - 零基础教程

WebRTC从入门到实践 - 零基础教程 目录 WebRTC简介 基础概念 工作原理 开发环境搭建 基础实践 三个实战案例 常见问题解答 1. WebRTC简介 1.1 什么是WebRTC&#xff1f; WebRTC&#xff08;Web Real-Time Communication&#xff09;是一个支持网页浏览器进行实时语音…...

破解路内监管盲区:免布线低位视频桩重塑停车管理新标准

城市路内停车管理常因行道树遮挡、高位设备盲区等问题&#xff0c;导致车牌识别率低、逃费率高&#xff0c;传统模式在复杂路段束手无策。免布线低位视频桩凭借超低视角部署与智能算法&#xff0c;正成为破局关键。该设备安装于车位侧方0.5-0.7米高度&#xff0c;直接规避树枝遮…...

Python 高效图像帧提取与视频编码:实战指南

Python 高效图像帧提取与视频编码:实战指南 在音视频处理领域,图像帧提取与视频编码是基础但极具挑战性的任务。Python 结合强大的第三方库(如 OpenCV、FFmpeg、PyAV),可以高效处理视频流,实现快速帧提取、压缩编码等关键功能。本文将深入介绍如何优化这些流程,提高处理…...

FFmpeg avformat_open_input函数分析

函数内部的总体流程如下&#xff1a; avformat_open_input 精简后的代码如下&#xff1a; int avformat_open_input(AVFormatContext **ps, const char *filename,ff_const59 AVInputFormat *fmt, AVDictionary **options) {AVFormatContext *s *ps;int i, ret 0;AVDictio…...