JAVA学习代码——重命名文件夹

对于文件夹的重命名需要注意:

1、重命名时输入的是文件夹路径,不要再文件夹后面添加"/"

2、新建文件是输入的是完整路径,创建的是文件所在位置的父路径,File dir = new File(filePath).getParentFile();

 如果不加getParentFile()将会创建全部路径,包括文件,但此时创建的是和文件名同名的文件夹,而不是文件,并且在使用时,比如写入数据时报错会

异常java.io.FileNotFoundException: 路径    (拒绝访问)

	public void savehtm(String htm, String fileName) {
//		String parentDir =	"rootDir//date//htm//"
		rootDir = String.format(Main.conf.getString("rootDir"), Main.date);
		String filePath = rootDir + Main.conf.getString("path_htm") + fileName + ".htm";
		if (htm != null) {
			File dir = new File(filePath).getParentFile();
			if (!dir.exists()) {
				dir.mkdirs();
			}
			try (FileOutputStream fos = new FileOutputStream(filePath);
					OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");) {
				osw.write(htm);
			} catch (IOException e) {
				logger.error("err", e);
			}
		}
	}

//判断文件夹是否存在,存在则重命名
	public void checkPath(){
		File f = new File(rootDir);
		if(f.exists()){
			File to = new File(rootDir+"_"+Main.time);
			f.renameTo(to);
		System.out.println("文件夹已存在,重命名为:"+to.getName());
		}
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值