java 用户想要将文件保存到 C 盘根目录时如何显示消息
How to display an message when user want to save a file in root of C Drive in java
我已经使用 JFileChooser 在我的 Application.I 中保存了一个文件,我观察到 JFileChooser 不会在没有任何通知的情况下将文件保存在 "C Drive" 的根目录中。所以,每当用户想在 "C Drive" 的根目录中保存文件时,我想向用户显示一条消息。我怎么知道用户选择的目录是 "C Drive" 的根目录。请帮助 me.Thank你.
您可以使用.getSelectedFile()
或.getSelectedFiles()
方法获取选中的文件。从文件中,您可以使用 .getPath()
获取文件路径,此 returns 文件路径作为字符串,现在您可以应用条件,让您知道所选文件是否在 C:/ drive
即使用户也只选择目录,这种方法也有效。在那种情况下,您必须使用 .getCurrentDirectory()
,此 returns 用户当前所在的目录。
小代码片段:
JFileChooser myFileChooser = new JFileChooser();
if(myFileChooser.getCurrentDirectory().getPath().equals("C:/")){
System.out.println("saving file here is not allowed");
}
您可以使用 JFileChooser#getSelectedFile
或 JFileChooser#getSelectedFiles
来获取选定的 File
,然后您可以将其与 File.listRoots
进行比较以确定选定的文件是否是根路径,例如...
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);
File selected = fc.getSelectedFile();
for (File f : File.listRoots()) {
if (selected.equals(f)) {
System.out.println("Is root path");
}
}
例如。
我已经使用 JFileChooser 在我的 Application.I 中保存了一个文件,我观察到 JFileChooser 不会在没有任何通知的情况下将文件保存在 "C Drive" 的根目录中。所以,每当用户想在 "C Drive" 的根目录中保存文件时,我想向用户显示一条消息。我怎么知道用户选择的目录是 "C Drive" 的根目录。请帮助 me.Thank你.
您可以使用.getSelectedFile()
或.getSelectedFiles()
方法获取选中的文件。从文件中,您可以使用 .getPath()
获取文件路径,此 returns 文件路径作为字符串,现在您可以应用条件,让您知道所选文件是否在 C:/ drive
即使用户也只选择目录,这种方法也有效。在那种情况下,您必须使用 .getCurrentDirectory()
,此 returns 用户当前所在的目录。
小代码片段:
JFileChooser myFileChooser = new JFileChooser();
if(myFileChooser.getCurrentDirectory().getPath().equals("C:/")){
System.out.println("saving file here is not allowed");
}
您可以使用 JFileChooser#getSelectedFile
或 JFileChooser#getSelectedFiles
来获取选定的 File
,然后您可以将其与 File.listRoots
进行比较以确定选定的文件是否是根路径,例如...
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);
File selected = fc.getSelectedFile();
for (File f : File.listRoots()) {
if (selected.equals(f)) {
System.out.println("Is root path");
}
}
例如。