Java中新建一个文件、目录及路径操作实例

 更新时间:2023年12月07日 11:27:38   作者:m0_45695898  
这篇文章主要给大家介绍了关于Java中新建一个文件、目录及路径操作的相关资料,新建文件、目录及路径是我们日常开发中经常会遇到的一个需求,本文通过示例代码介绍的非常详细,需要的朋友可以参考下

前言

学习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

附:java根据路径创建文件夹

import java.io.File;

public class CreateFolderExample {
    public static void main(String[] args) {
        String folderPath = "path/to/folder";
        File folder = new File(folderPath);
        
        if (folder.exists()) {
            System.out.println("文件夹已存在");
            return;
        }
        
        if (folder.mkdir()) {
            System.out.println("文件夹创建成功");
        } else {
            System.out.println("文件夹创建失败");
        }
    }
}

到此这篇关于Java中新建一个文件、目录及路径的文章就介绍到这了,更多相关Java新建文件目录路径内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现线程同步方法及原理详解

    Java实现线程同步方法及原理详解

    这篇文章主要介绍了Java实现线程同步方法及原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • SpringMVC实现简单跳转方法(专题)

    SpringMVC实现简单跳转方法(专题)

    这篇文章主要介绍了SpringMVC实现简单跳转方法(专题),详细的介绍了SpringMVC跳转的几种方法,非常具有实用价值,需要的朋友可以参考下
    2018-03-03
  • Mybatis resultMap标签继承、复用、嵌套方式

    Mybatis resultMap标签继承、复用、嵌套方式

    这篇文章主要介绍了Mybatis resultMap标签继承、复用、嵌套方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • 浅谈String类型等值比较引起的“==”、“equals()”和“hashCode”思考

    浅谈String类型等值比较引起的“==”、“equals()”和“hashCode”思考

    这篇文章主要介绍了浅谈String类型等值比较引起的“==”、“equals()”和“hashCode”思考。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Spring中@ConditionalOnProperty注解的作用详解

    Spring中@ConditionalOnProperty注解的作用详解

    这篇文章主要介绍了Spring中@ConditionalOnProperty注解的作用详解,@ConditionalOnProperty注解主要是用来判断配置文件中的内容来决定配置类是否生效用的,如果条件不匹配,则配置类不生效,需要的朋友可以参考下
    2024-01-01
  • java项目实现猜拳小游戏

    java项目实现猜拳小游戏

    这篇文章主要为大家详细介绍了java项目实现猜拳小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-05-05
  • win10操作系统下重启电脑java环境变量失效

    win10操作系统下重启电脑java环境变量失效

    这篇文章主要介绍了win10操作系统下重启电脑java环境变量失效,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • 简单了解spring bean作用域属性singleton和prototype的区别

    简单了解spring bean作用域属性singleton和prototype的区别

    这篇文章主要介绍了简单了解spring bean作用域属性singleton和prototype的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • Spring创建IOC容器的方式解析

    Spring创建IOC容器的方式解析

    这篇文章主要介绍了Spring创建IOC容器的方式解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • spring获取bean的源码解析

    spring获取bean的源码解析

    这篇文章主要介绍了spring获取bean的源码解析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-04-04

最新评论