Java - 从文件夹中获取没有扩展名的文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30187581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Getting file name without extension from a folder
提问by Hyperion
I'm using this code to get the absolute path of files inside a folder
我正在使用此代码获取文件夹内文件的绝对路径
public void addFiles(String fileFolder){
ArrayList<String> files = new ArrayList<String>();
fileOp.getFiles(fileFolder, files);
}
But I want to get only the file name of the files (without extension). How can I do this?
但我只想获取文件的文件名(没有扩展名)。我怎样才能做到这一点?
回答by Thirumalai Parthasarathi
i don't think such a method exists. you can get the filename and get the last index of .
and truncate the content after that and get the last index of File.separator
and remove contents before that.
我认为不存在这样的方法。您可以获取文件名并获取最后一个索引.
并在此之后截断内容,然后获取最后一个索引File.separator
并在此之前删除内容。
you got your file name.
你有你的文件名。
or you can use FilenameUtils
from apache commons IOand use the following
或者您可以使用FilenameUtils
来自apache commons IO并使用以下内容
FilenameUtils.removeExtension(fileName);
FilenameUtils.removeExtension(fileName);
回答by Callum McKinnon-Snell
There's a really good way to do this - you can use FilenameUtils.removeExtension.
有一个非常好的方法可以做到这一点 - 您可以使用FilenameUtils.removeExtension。
Also, See: How to trim a file extension from a String
另请参阅:如何从字符串中修剪文件扩展名
回答by akhil_mittal
This code will do the work of removing the extension and printing name of file:
此代码将完成删除文件扩展名和打印名称的工作:
public static void main(String[] args) {
String path = "C:\Users\abc\some";
File folder = new File(path);
File[] files = folder.listFiles();
String fileName;
int lastPeriodPos;
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
fileName = files[i].getName();
lastPeriodPos = fileName.lastIndexOf('.');
if (lastPeriodPos > 0)
fileName = fileName.substring(0, lastPeriodPos);
System.out.println("File name is " + fileName);
}
}
}
If you are ok with standard libraries then use Apache Common as it has ready-made method for that.
如果您对标准库没问题,那么请使用 Apache Common,因为它有现成的方法。
回答by Jeff Padgett
String filePath = "/storage/emulated/0/Android/data/myAppPackageName/files/Pictures/JPEG_20180813_124701_-894962406.jpg"
String nameWithoutExtension = Files.getNameWithoutExtension(filePath);