Remove filename extension in Java

后端 未结 10 2234
你的背包
你的背包 2020-12-09 08:48

(Without including any external libraries.)

What\'s the most efficient way to remove the extension of a filename in Java, without assuming anything of the f

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 09:33

    Use new Remover().remove(String),

    jdb@Vigor14:/tmp/stackoverflow> javac Remover.java && java Remover
    folder > folder
    hello.txt > hello
    read.me > read
    hello.bkp.txt > hello.bkp
    weird..name > weird.
    .hidden > .hidden
    

    Remover.java,

    import java.util.*;
    
    public class Remover {
    
        public static void main(String [] args){
            Map tests = new LinkedHashMap();
            tests.put("folder", "folder");
            tests.put("hello.txt", "hello");
            tests.put("read.me", "read");
            tests.put("hello.bkp.txt", "hello.bkp");
            tests.put("weird..name", "weird.");
            tests.put(".hidden", ".hidden");
    
            Remover r = new Remover();
            for(String in: tests.keySet()){
                String actual = r.remove(in);
                log(in+" > " +actual);
                String expected = tests.get(in);
                if(!expected.equals(actual)){
                    throw new RuntimeException();
                }
            }
        }
    
        private static void log(String s){
            System.out.println(s);
        }
    
        public String remove(String in){
            if(in == null) {
                return null;
            }
            int p = in.lastIndexOf(".");
            if(p <= 0){
                return in;
            }
            return in.substring(0, p);
        }
    }
    

提交回复
热议问题