有没有在Java中的方式来确定路径是否有效,而不尝试创建一个文件? [英] Is there a way in Java to determine if a path is valid without attempting to create a file?

查看:162
本文介绍了有没有在Java中的方式来确定路径是否有效,而不尝试创建一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定用户提供的字符串是否是一个有效的文件路径(即,如果createNewFile()将成功或抛出一个异常),但我不想膨胀文件系统创建无用的文件只是为了验证的目的,那么有没有一种方法来确定是否我的字符串是一个有效的文件路径而不试图创建文件?

我知道有效的文件路径的定义,但是我想知道是否有任何快速接受C:/ foo或/ foo和拒绝香蕉的方法...一种可能的方法可能是尝试创建文件并最终删除它如果创建成功,但我希望有一个更优雅的方式来实现相同的结果...

解决方案

检查目录是否存在。

 档案档案=新档案(c:\\cygwin\ \cygwin.bat); 
if(!file.isDirectory())
file = file.getParentFile();
if(file.exists()){
...
}


$ b $看起来像file.canWrite()没有给你一个明确的指示,如果你有权限写入目录。


I need to determine if a user-supplied String is a valid file path (i.e. if createNewFile() will succeed or throw an Exception) but i don't want to bloat the file system with useless files created just for validation purposes, so is there a way to determine if the String i have is a valid file path without attempting to create the file?

I know the definition of "valid file path" varies depending on the OS, but i was wondering if there was any quick way of accepting "C:/foo" or "/foo" and rejecting "banana"...a possible approach may be attempting to create the file and eventually deleting it if the creation succeeded, but i hope there is a more elegant way of achieving the same result...

解决方案

This would check for the existance of the directory as well.

File file = new File("c:\\cygwin\\cygwin.bat");
if (!file.isDirectory())
   file = file.getParentFile();
if (file.exists()){
    ...
}

It seems like file.canWrite() does not give you a clear indication if you have permissions to write to the directory.

这篇关于有没有在Java中的方式来确定路径是否有效,而不尝试创建一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆