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

news2024/9/28 17:32:37

文章目录

  • 前言
  • 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 fileName
	String directoryPath;
	// the name of the fileName
	String 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 path
		FileTest1.createAFileInCurrentPath("DefaultJavaFile1.java", ".");
		
		//create a file in certain path
		File testFile1 = new File(existedPath1, testFileName1);
		FileTest1.createAFileInCertainPath(testFile1);
		
	}
}

FileTest1.java

import java.io.*;



class FileTest1{
	// the path of the fileName
	String directoryPath;
	// the name of the fileName
	String 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 path
		FileTest1.createAFileInCurrentPath("DefaultJavaFile1.java", ".");
		
		//create a file in certain and existed path
		File testFile1 = new File(existedPath1, testFileName1);
		FileTest1.createAFileInCertainPath(testFile1);
		//create a file in certain but not existed path
		File testFile2 = new File(unExistedPath1, testFileName2);
		FileTest1.createAFileInCertainPath(testFile2);
	}
}

FileTest1.java

import java.io.*;



class FileTest1{
	// the path of the fileName
	String directoryPath;
	// the name of the fileName
	String 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 path
		FileTest1.createAFileInCurrentPath("DefaultJavaFile1.java", ".");
		
		//create a file in certain and existed path
		File testFile1 = new File(existedPath1);
		FileTest1.createAFileInCertainPath(testFile1);
		
		//create a file in certain but not existed path
		
		FileTest1.createAFileInCertainPath(testFileName2, unExistedPath1);
		
		
	}
}

FileTest1.java

import java.io.*;



class FileTest1{
	// the path of the fileName
	String directoryPath;
	// the name of the fileName
	String 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 path
		File testFile1 = new File(existedPath1);
		FileTest1.createAFileInCertainPath(testFile1);
		
		//create a file in certain but not existed path
		FileTest1.createAFileInCertainPath(testFileName2, unExistedPath1);
		
		//delete a file in current path
		FileTest1.deleteAFileInCurrentPath("DefaultJavaFile1.java");
		
		//delete a file in certain path
		String deleteTestPath1 = "D:\\TestPath1\\TestDir1\\TestDir2\\TestDir3\\TestDir3_1\\测试.txt";
		FileTest1.deleteAFileInCeratainPath("D:\\TestPath1\\TestDir1\\TestDir2\\TestDir3\\TestDir3_1", "测试.txt");
		
		//delete a dir in certain path
		FileTest1.deleteADirInCertainPath("D:\\TestPath1\\TestDir1\\TestDir2\\TestDir3\\TestDir3_2");
		
	}
}

FileTest1.java

import java.io.*;



class FileTest1{
	// the path of the fileName
	String directoryPath;
	// the name of the fileName
	String 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.coloradmin.cn/o/371226.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ASE40N50SH-ASEMI高压MOS管ASE40N50SH

编辑-Z ASE40N50SH在TO-247封装里的静态漏极源导通电阻(RDS(ON))为100mΩ,是一款N沟道高压MOS管。ASE40N50SH的最大脉冲正向电流ISM为160A,零栅极电压漏极电流(IDSS)为1uA,其工作时耐温度范围为-55~150摄氏度。ASE40N…

【架构师】零基础到精通——架构发展

博客昵称:架构师Cool 最喜欢的座右铭:一以贯之的努力,不得懈怠的人生。 作者简介:一名Coder,软件设计师/鸿蒙高级工程师认证,在备战高级架构师/系统分析师,欢迎关注小弟! 博主小留言…

PHP - ChatGpt API 接入 ,代码,亲测!(最简单!)

由于最近ChatGpt 大火,但是门槛来说是对于大家最头疼的环节, 我自己也先开发了一个个人小程序!大家可以访问使用下, 由此ChatGpt 有一个API 可以仅供大伙对接 让我来说下资质: 1:首先要搞得到一个 ChatGp…

HttpRunner接口自动化测试框架--常见问题

本篇文章主要总结在使用httprunner框架做接口自动化测试过程中遇到的问题 官方的问题总结:Issues httprunner/httprunner GitHub 1.在参数化过程中读取CSV文件,不能读取出整型来。 读取下方文件数据,全部是字符串格式 原因:c…

操作系统(复试准备)

操作系统(复试准备) 第一章知识点 操作系统概述 操作系统的概念 负责协调软硬件等计算机资源的工作 为上层用户,应用程序提供简单易用的接口 是一种系统软件 操作系统的功能与目标 资源的管理者 处理机管理,存储器管理&#x…

Linux 基础知识:指令与shell

目录一、操作系统二、指令三、shell一、操作系统 什么是操作系统? 单纯的操作系统应该是指操作系统内核。内核的作用就是管理计算机的软硬件资源,让计算机在合适的时候干合适的事情。 但是有一个问题,并不是人人都会直接通过内核来操作计算机…

异常信息记录入库

方案介绍 将异常信息放在日志里面,如果磁盘定期清理,会导致很久之前的日志丢失,因此考虑将日志中的异常信息存在表里,方便后期查看定位问题。 由于项目是基于SpringBoot构架的,所以采用AdviceControllerExceptionHand…

【跟着ChatGPT学深度学习】ChatGPT带我入门深度学习

❤️觉得内容不错的话,欢迎点赞收藏加关注😊😊😊,后续会继续输入更多优质内容❤️👉有问题欢迎大家加关注私戳或者评论(包括但不限于NLP算法相关,linux学习相关,读研读博…

树与二叉树与森林的相关性质

文章目录树的度树的性质二叉树的性质二叉树与森林树的度 树的度指的是树内所有节点的度数的最大值。 节点的度:节点所拥有的子树的数量。简单来说,我们直接数分支即可,例如下图: 在这颗二叉树中,节点2的度为2&#…

【Java】Synchronized锁原理和优化

一、synchronized介绍 synchronized中文意思是同步,也称之为”同步锁“。 synchronized的作用是保证在同一时刻, 被修饰的代码块或方法只会有一个线程执行,以达到保证并发安全的效果。 synchronized是Java中解决并发问题的一种最常用的方法…

K3S系列文章-使用AutoK3s在腾讯云上安装高可用K3S集群

开篇 《K3s 系列文章》《Rancher 系列文章》 方案 在腾讯云上安装 K3S 后续会在这套 K3S 集群上安装 Rancher 方案目标 高可用3 台master 的 k3s 集群 数据备份k3s 数据备份到 腾讯云对象存储 cos 尽量复用公有云的能力Tencent Cloud Controller Manager (❌ 因为腾讯云已…

【LINUX】环境变量以及main函数的参数

文章目录前言环境变量常见环境变量:设置环境变量:和环境变量相关的命令:环境变量的组织方式:获取环境变量环境变量可以被子进程继承环境变量总结main函数的参数前言 大家好久不见,今天分享的内容是环境变量和main函数…

JUC并发编程与源码分析笔记09-原子类操作之十八罗汉增强

基本类型原子类 AtomicInteger、AtomicBoolean、AtomicLong。 常用API: public final int get();// 获取当前的值 public final int getAndSet(int newValue);// 获取当前值,并设置新值 public final int getAndIncrement();// 获取当前的值&#xff0…

2.25Maven的安装与配置

一.Mavenmaven是一个Java世界中,非常知名的"工程管理工具"/构建工具"核心功能:1.管理依赖在进行一个A 操作之前,要先进行一个B操作.依赖有的时候是很复杂的,而且是嵌套的2.构建/编译(也是在调用jdk)3. 打包把java代码给构建成jar或者warjar就是一个特殊的压缩包…

【基础算法】二分例题(我在哪?)

🌹作者:云小逸 📝个人主页:云小逸的主页 📝Github:云小逸的Github 🤟motto:要敢于一个人默默的面对自己,强大自己才是核心。不要等到什么都没有了,才下定决心去做。种一颗树,最好的时间是十年前…

元宇宙+教育,正在引发哪些剧烈变革?机会在哪里?丨圆桌实录

图片来源:由无界AI绘画工具生成2月23日,温州元宇宙创新中心为2023年第一批申请入驻的项目企业举办了签约仪式。温州临境网络科技有限公司、温州好玩文化产业有限公司、温州云兮科技有限公司(筹)等企业完成签约。这意味着&#xff…

Spring 事务管理详解及使用

✅作者简介:2022年博客新星 第八。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏…

Vue模态框的封装

一、模态框1、模态框:若对话框不关闭,不能操作其父窗口2、非模态框:对话框不关闭,可以操作其窗口二、Vue组件实现模态框的功能1、模态框是一个子组件2、显示和隐藏由父组件决定3、对话框的标题也是由父组件传递的4、对话框的主显示…

OpenAPI SDK组件之Spring Aop源码拓展

Spring Aop 看这个分享的应该都用过Spring Aop,这里就不再过多介绍了它是什么了。 我抽取了Spring Aop的部分源码,通过它实现请求参数可变拦截,同时apisdk离开Spring框架,仍然可以正常运行。 讲拦截也好,通知也罢&a…

[蓝桥杯 2022 国 B] 卡牌(贪心/二分)

题目传送门 该题第一思路是想去模拟题目中所描述的过程 这里我选择从大到小遍历可能凑出的牌套数&#xff0c;计算凑出它需要补的牌数以及判断是否会超出能补的牌数 #include<iostream> #include<climits> #include<vector> #include<algorithm> #def…