首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取“最近的文件”中带有两个点的文件名的文件

获取“最近的文件”中带有两个点的文件名的文件
EN

Stack Overflow用户
提问于 2018-07-24 16:30:05
回答 2查看 171关注 0票数 0

我的java应用程序中有一个“打开最近的文件”按钮,我似乎无法显示文件名中有两个点的文件(例如,sample.file.tpp)。不过,文件名中的一个点工作得很好。我尝试在String[] ext = f.getName().split()中使用正则表达式参数,但什么都不起作用。代码如下。请帮帮忙。谢谢。

代码语言:javascript
复制
public File showOpenDialog(Window ownerWindow){

    //ppt.load();

    fc.setInitialDirectory(ppt.getCurrent().toFile());

    File f = fc.showOpenDialog(ownerWindow);

    // Recent file settings
    if(f!=null){
        ppt.setCurrent(f.getParentFile().toString()) ;
        ppt.addLately(f);

        if(ppt.getLately()!=null){
            setMenuItems();

        }else{
        }


        String[] ext = f.getName().split("\\.");

        System.out.println(ext.length);

        if(ext.length > 1)
            if(ext[1].equals("tpp")){ 
                Main.setFileName(f.getName());
                saved = true;
            }

    }

    ppt.store();

    return f;
}



/**
 * Recent file settings
 * Returns null if it is not tpp file
 */
public File fileOpen(File f){
    ppt.load();

    fc.setInitialDirectory(ppt.getCurrent().toFile());

    // Recent file settings
    if(f!=null){
        ppt.setCurrent(f.getParentFile().toString()) ;
        ppt.addLately(f);

        if(ppt.getLately()!=null){
            setMenuItems();

        }else{
        }


        String[] ext = f.getName().split("\\.");

        System.out.println(ext.length);

        if(ext.length > 1)
            if(ext[1].equals("tpp")){ 
                Main.setFileName(f.getName());
                saved = true;
            }else return null;
        else return null;

    }
    ppt.store();
    return f;
}



public File showSaveDialog(Window ownerWindow){

    ppt.load();

    fc.setInitialDirectory(ppt.getCurrent().toFile());

    File f = fc.showSaveDialog(ownerWindow);


    // Recent file settings
    if(f!=null){
        ppt.setCurrent(f.getParentFile().toString()) ;
        ppt.addLately(f);

        if(ppt.getLately()!=null){
            setMenuItems();

        }else{
        }

        String[] ext = f.getName().split("\\.");

        System.out.println(ext.length);

        if(ext.length > 1)
            if(ext[1].equals("tpp")){
                Main.setFileName(f.getName());
                saved = true;
            }
    }

    ppt.store();

    return f;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-24 16:50:53

代替if(ext[1].equals("tpp"))...

你应该做if(ext[length-1].equals("tpp"))..

这是因为如果你的文件名是sample.file.tpp,在拆分名称时,你会得到一个包含三个元素的数组:samplefiletpp

正如你在这里看到的,tpp将是数组中的第三个元素(即.索引= 2)。因此,您可以使用ext[2],或者对于包含两个以上点的情况,使用length-1,因为文件扩展名始终在最后。

票数 0
EN

Stack Overflow用户

发布于 2018-07-24 16:35:39

我认为在这种情况下不需要regexp:

代码语言:javascript
复制
f.getName().endsWith(".tpp")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51493987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档