[英]Extract file name from list
During loop my list contains csv files, I want to get file name, under which I will save my output. 在循环期间,我的列表包含csv文件,我想获取文件名,在该文件名下将保存输出。
Example : 范例 :
File list: t1.csv
, t2.csv
, t3.csv
文件列表:
t1.csv
, t2.csv
, t3.csv
Output list should look: t1.xml, t2.xml, t3.xml
输出列表应如下所示:
t1.xml, t2.xml, t3.xml
sample.java sample.java
List<String> csvFiles = new ArrayList<String>();
try {
File[] files = new File(textCSV.getText()).listFiles();
for (File file : files) {
if (file.isFile()) {
csvFiles.add(file.getName());
}
}
for(int i=0;i<csvFiles.size();i++) {
System.out.println(csvFiles.get(i));
String Output = ".xml" //how to put here csv name
}
}
You can rewrite like this. 您可以这样重写。
List<String> csvFiles = new ArrayList<String>();
try {
File[] files = new File(textCSV.getText()).listFiles();
for (File file : files) {
if (file.isFile()) {
csvFiles.add(file.getName());
}
}
for(int i=0;i<csvFiles.size();i++)
{
System.out.println(csvFiles.get(i));
String Output = csvFiles.get(i).substring(0, csvFiles.get(i).indexOf(".")) + ".xml" //how to put here csv name
}
}
There are 3 ways that I can think of where you can extract only the filename. 我可以通过3种方式想到仅提取文件名的位置。
Using Apache Commons Library 使用Apache Commons库
FilenameUtils.removeExtension(file.getName());
In case your files will always contain at least one extension (at least one "." in the file name) 如果您的文件将始终包含至少一个扩展名 (文件名中至少包含一个“。”)
file.getName().substring(0, file.getName().lastIndexOf("."));
In case there are files which don't contain any extension 如果某些文件不包含任何扩展名
int index = file.getName().lastIndexOf("."); if (index == -1) { file.getName(); } else { file.getName().substring(0, index); }
You can replace your csvFiles.add(file.getName());
您可以替换
csvFiles.add(file.getName());
to csvFiles.add();
到
csvFiles.add();
with argument as any of the above lines. 与上述任何一行一样带有参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.