Extract file name from list

191 views Asked by At

During loop my list contains csv files, I want to get file name, under which I will save my output.

Example:

File list: t1.csv, t2.csv, t3.csv

Output list should look: t1.xml, t2.xml, t3.xml

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
    }
}
2

There are 2 answers

1
tam nguyen On BEST ANSWER

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
        }
    }
0
Kishore Bandi On

There are 3 ways that I can think of where you can extract only the filename.

  1. Using Apache Commons Library

    FilenameUtils.removeExtension(file.getName());
    
  2. 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("."));
    
  3. 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()); to csvFiles.add(); with argument as any of the above lines.