简体   繁体   中英

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.

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

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.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM