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

news/2024/4/17 4:05:53/文章来源:https://blog.csdn.net/m0_45695898/article/details/129212728

文章目录

  • 前言
  • 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_74053.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Fiddler报文分析-断点应用、模拟网络限速-HTTPS的 拦截

目录 一、报文分析 Statistics 请求性能数据 检查器(Inspectors) 自定义响应(AutoResponder) Composer Composer的功能就是用来创建HTTP Request然后发送请求。 允许自定义请求发送到服务器,即可以手动创建一个新…

大学毕业后,送了2个月外卖,哭了一整晚

先简单介绍一下自己,我来自湛江,大学学的的物流管理专业,现在就职于一家互联网公司,从事软件测试工作。 我来自湛江的一个偏远农村,家里兄弟姐妹多,父母无力负担我的学费,很多时候学费都是靠姐…

CHATGPT是新的“搜索引擎终结者”吗?百度是否慌了

ChatGPT 以其非凡的自然语言处理 (NLP) 能力和清晰的响应风靡全球,有望带来一场重大的技术革命。在不知不觉中,叙事转向了ChatGPT与百度的对决,因为来自OpenAI的智能和健谈的聊天机器人已经慢慢获得了“潜在的百度终结…

JS 执行机制 详解(附图)

一、JS是单线程JS语言的一大特点就是单线程,也就是说,同一个时间只能做一件事。这是JS这门脚本语言诞生的使命所致——用来处理页面中用户的交互,以及操作DOM而诞生的。单线程就意味着,所有任务需要排队,前一个任务结束…

自动化测试整理 --- STAF/STAX Robot Framework

题记:上周花了点时间学习开源的自动化测试框架Robot Framework,结合自己之前的自动化经验,就想周末写篇文章整理下。 目前,所在项目的自动化测试框架是基于STAF/STAX的拓展,围绕STAX执行引擎,扩展了测试用例的创建、管理&#xf…

CMake调试器出炉:调试你的CMake脚本

Visual Studio 开发团队一直和 Kitware 紧密合作,致力于开发一个用于调试 CMake 脚本的调试器。 我们将继续这个工作,以便开发人员社区可以通过添加新功能和对其他 DAP 功能的支持来共同改进它。 我们很高兴地宣布,CMake 调试器的预览版现在…

验证功能覆盖率收集时per_instance=1可能导致覆盖率线性增长

验证覆盖率收集时,发现coverage database达到了惊人的256G,如下: 进入database中的testdata目录下的用例定位发现,问题出在这个文件: testbench.inst.xml其大小基本等同于验证用例覆盖率的大小。 这个文件时怎么产…

用数据讲故事:基于分析场景的17条Python使用小结

数据科学的编程需要非常灵活的语言,以最少的代码处理复杂的数据建模场景。作为一名数科小白,我对Python的第一认知是丰富的机器学习算法,但Python有超过12万个第三方库,覆盖从数据预处理、统计分析、数据挖掘及可视化等各种日常数…

Android Studio中创建java工程

1. 前言 电脑环境: Ubuntu 18.04 开发工具环境:Android Studio 4.1.3 版本 经常要使用验证Java API, 把配置环境步骤记录一下 2. 创建步骤 2.1 新建一个Android Studio App工程 New ---> New Project ---> 选择一个Activity主题---> Finish 就创建ok 2.2 …

【模拟集成电路】分频器(DIV_TSPC)设计

分频器(DIV_TSPC)设计前言一、DIV工作原理二、DIV电路设计(1)32分频原理图(2)D触发器原理图(3)D锁存器原理图(4)三输入与非门原理图三、DIV仿真测试32分频器测…

【模拟集成电路】宽摆幅压控振荡器(VCO)设计

鉴频鉴相器设计(Phase Frequency Detector,PFD)前言一、VCO工作原理二、VCO电路设计VCO原理图三、压控振荡器(VCO)测试VCO测试电路图瞬态测试(1)瞬态输出(2)局部放大图&a…

调试版获取安卓SHA1值

确保你的电脑上有JDK,配置好环境变量后执行我这些步骤。where keytool看看电脑找不找得到找得到就可以进行下一步了口令默认android或者为空

javaEE 初阶 — 关于 IPv4、IPv6 协议、NAT(网络地址转换)、动态分配 IP 地址 的介绍

文章目录1. IPv42. IPv63. NAT4. 动态分配 IP 地址1. IPv4 在互联网的世界中只有 0 和1 ,所以每个人都有一个由 0 和 1 组成的地址来让别人找到你。 这段由 0 和 1 组成的地址叫 IP 地址,这是互联网的基础资源,可以简单的理解为互联网的土地。…

【Acwing 周赛复盘】第91场周赛复盘(2023.2.18)

【Acwing 周赛复盘】第91场周赛复盘(2023.2.18) 周赛复盘 ✍️ 本周个人排名:1286/3115 AC情况:2/3 这是博主参加的第六次周赛,周赛当晚有事,是后来定时自测的 😂 在 20 分钟内 AC 了 2 题&…

数据库|(六)连接查询

(六)连接查询1. 笛卡尔乘积2. 连接查询分类2.1 按年代分2.2 按功能分3. 等值连接(sql 92标准)3.1 特点3.2 一般使用3.3 为表取别名3.4 两表顺序可以调换3.5 可以加筛选3.6 可以加分组3.7 可以加排序3.8 可以实现三表连接4. 非等值连接(sql 92标准)5. sql…

LeetCode练习三:链表

文章目录一、链表基础1.1 无序表(UnorderedList)1.1.2 双向链表1.1.3 循环链表1.2 链表的基本操作1.2.1 定义链表结构1.2.2 建立线性链表1.2.3 求线性链表的长度1.2.4 查找元素1.2.5 插入元素1.2.6 改变元素1.2.7 删除元素1.3 有序表OrderedList1.4 链表…

39-Golang中的接口

Golang中的接口基本介绍基本语法注意事项和细节案例实现对Hero结构体切片的排序:sort.Sort(data Interface)实现接口和继承之间的比较区别基本介绍 interface类型可以定义一组方法,但是这些不需要实现。并且interface不能包含任何变量。到某个自定义类型…

直接在ide启动mitmproxy监听,脱离命令行启动,懒人福音

前言 本文解决了只能通过命令行启动 mitmproxy 的痛点。 在使用 mitmproxy 时候存在这样一个问题,就是每次启动它时候都需要通过命令行启动。 加上最近有位读者向我提问(以前也有读者提问该问题):不通过命令行如何启动 mitmproxy监…

XML调用 CAPL Test Function

🍅 我是蚂蚁小兵,专注于车载诊断领域,尤其擅长于对CANoe工具的使用🍅 寻找组织 ,答疑解惑,摸鱼聊天,博客源码,点击加入👉【相亲相爱一家人】🍅 玩转CANoe&…

阿里限量出产Elasticsearch学习手册,确定不心动?

前言只有光头才能变强。不知道大家的公司用Elasticsearch多不多,反正我公司的是有在用的。平时听同事们聊天肯定避免不了不认识的技术栈,例如说:把数据放在引擎,从引擎取出数据等等。如果对引擎不了解的同学,就压根听不…