我的java应用程序中有一个“打开最近的文件”按钮,我似乎无法显示文件名中有两个点的文件(例如,sample.file.tpp)。不过,文件名中的一个点工作得很好。我尝试在String[] ext = f.getName().split()中使用正则表达式参数,但什么都不起作用。代码如下。请帮帮忙。谢谢。
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;
}发布于 2018-07-24 16:50:53
代替if(ext[1].equals("tpp"))...
你应该做if(ext[length-1].equals("tpp"))..
这是因为如果你的文件名是sample.file.tpp,在拆分名称时,你会得到一个包含三个元素的数组:sample,file和tpp。
正如你在这里看到的,tpp将是数组中的第三个元素(即.索引= 2)。因此,您可以使用ext[2],或者对于包含两个以上点的情况,使用length-1,因为文件扩展名始终在最后。
发布于 2018-07-24 16:35:39
我认为在这种情况下不需要regexp:
f.getName().endsWith(".tpp")https://stackoverflow.com/questions/51493987
复制相似问题