java 检查文件扩展名是否为.txt的程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14536377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Program to check whether extension of a file is .txt
提问by zealouscoder
I wrote a java code having an awt text field and a button, where if I click on the button, I can browse a file using JFileChooser. It needs to check whether the file has ".txt" extension or not.I wrote the code below, but it is not getting verified.
我编写了一个带有 awt 文本字段和一个按钮的 java 代码,如果我点击按钮,我可以使用 JFileChooser 浏览文件。它需要检查文件是否有“.txt”扩展名。我写了下面的代码,但没有得到验证。
Where am I going wrong? Please help to determine where I am wrong.
我哪里错了?请帮助确定我错在哪里。
try{
final JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
chooser.addChoosableFileFilter(new FileFilter() {
public String getDescription() {
return "*.txt";
}
public boolean accept(File filename)
{
if(filename.getName().endsWith(".txt")){
return true;
}
else{
System.out.println("Browsed dest file extension must be .txt");
return false;
}}
});
catch(Exception ex)
{
JOptionPane.showMessageDialog(f,"Exception occurred");
}
回答by emka86
Your problem is that:
你的问题是:
chooser.showOpenDialog(null);
stop execution of code until user select a file. Add this line after adding FileFilter
and eveyrthing should work ok.
停止执行代码,直到用户选择一个文件。添加后添加此行FileFilter
,一切都应该可以正常工作。
Little explanation:
小解释:
Method showOpenDialog(Component c)
blockexecution of current thread until user action and next line of your code will be executed after the user choose a file. If you invoke after adding a FileFilter
once again showOpenDialog
it will work as you expect.
方法showOpenDialog(Component c)
blockexecution of current thread直到用户操作,并且在用户选择文件后将执行下一行代码。如果您在FileFilter
再次添加后调用showOpenDialog
,它将按您的预期工作。
回答by Michael
I would suggest using the @Override
annotation for the accept
method - see this link @Override explained in Oracle Documentation.
我建议使用该方法的@Override
注释accept
- 请参阅Oracle 文档中解释的此链接@Override。
Plus, it would be best to use filename.getName().toLowerCase().endsWith(".txt")
instead filename.getName().endsWith(".txt")
to ensure that files with the extension .TXT
will pass the filter as well.
此外,这将是最好的使用filename.getName().toLowerCase().endsWith(".txt")
,而不是filename.getName().endsWith(".txt")
确保与扩展的文件.TXT
将通过筛选器。