如何获取没有Java扩展名的File对象的名称? [英] How to get name of File object without its extension in Java?
问题描述
我正在尝试获取没有扩展名的文件
对象的名称,例如文件名是vegetation.txt时得到植被。我尝试过实现此代码:
I am trying to get name of a File
object without its extension, e.g. getting "vegetation" when the filename is "vegetation.txt." I have tried implementing this code:
openFile = fileChooser.getSelectedFile();
String[] tokens = openFile.getName().split(".");
String name = tokens[0];
不幸的是,它返回一个 null
对象。我想,在定义 String
对象时会出现问题,因为方法 getName()
正常工作;它给我带有扩展名的文件名。
Unfortunately, it returns a null
object. There is a problem just in the defining the String
object, I guess, because the method getName()
works correctly; it gives me the name of the file with its extension.
你有什么想法吗?
推荐答案
如果你想自己实现,试试这个:
If you want to implement this yourself, try this:
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
name = name.substring(0, pos);
}
(此变体不会为输入文件名留下空字符串比如.txt。如果你希望在这种情况下字符串为空,请将> 0
更改为> = 0
。)
(This variation doesn't leave you with an empty string for an input filename like ".txt". If you want the string to be empty in that case, change > 0
to >= 0
.)
您可以替换 if
语句使用条件表达式的赋值,如果您认为它使您的代码更具可读性;以@ Steven的答案为例。 (我不认为它......但这是一个意见问题。)
You could replace the if
statement with an assignment using a conditional expression, if you thought it made your code more readable; see @Steven's answer for example. (I don't think it does ... but it is a matter of opinion.)
可以说是一个更好的想法使用其他人编写和测试的实现。 Apache FilenameUtils
是一个不错的选择;请参阅@ slachnick的答案,以及链接的Q& A。
It is arguably a better idea to use an implementation that someone else has written and tested. Apache FilenameUtils
is a good choice; see @slachnick's Answer, and also the linked Q&A.
这篇关于如何获取没有Java扩展名的File对象的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!