下面列出了怎么用javax.swing.filechooser.FileSystemView的API类实例代码及写法,或者点击链接到github查看源代码。
protected void doDirectoryChanged(final PropertyChangeEvent e) {
JFileChooser fc = getFileChooser();
FileSystemView fsv = fc.getFileSystemView();
clearIconCache();
File currentDirectory = fc.getCurrentDirectory();
if (currentDirectory != null) {
directoryComboBoxModel.addItem(currentDirectory);
if (fc.isDirectorySelectionEnabled() && !fc.isFileSelectionEnabled()) {
if (fsv.isFileSystem(currentDirectory)) {
setFileName(currentDirectory.getPath());
} else {
setFileName(null);
}
}
}
}
protected void doDirectoryChanged(final PropertyChangeEvent e) {
getDetailsTableModel().updateColumnInfo();
JFileChooser fc = getFileChooser();
FileSystemView fsv = fc.getFileSystemView();
applyEdit();
resetEditIndex();
ensureIndexIsVisible(0);
File currentDirectory = fc.getCurrentDirectory();
if (currentDirectory != null) {
if (!readOnly) {
getNewFolderAction().setEnabled(canWrite(currentDirectory, getFileChooser()));
}
fileChooserUIAccessor.getChangeToParentDirectoryAction().setEnabled(!fsv.isRoot(currentDirectory));
}
if (list != null) {
list.clearSelection();
}
}
public static void main(String[] args) {
File dir = FileSystemView.getFileSystemView().getDefaultDirectory();
printDirContent(dir);
System.setSecurityManager(new SecurityManager());
// The next test cases use 'dir' obtained without SecurityManager
try {
printDirContent(dir);
throw new RuntimeException("Dir content was derived bypass SecurityManager");
} catch (AccessControlException e) {
// It's a successful situation
}
}
public static void main(String[] args) {
File dir = FileSystemView.getFileSystemView().getDefaultDirectory();
printDirContent(dir);
System.setSecurityManager(new SecurityManager());
// The next test cases use 'dir' obtained without SecurityManager
try {
printDirContent(dir);
throw new RuntimeException("Dir content was derived bypass SecurityManager");
} catch (AccessControlException e) {
// It's a successful situation
}
}
/**
* Figure out where the Raccoon homedir is
*
* @return the top level raccoon folder
*/
private static File whereami() {
// Does the user want the Raccoon dir to be in a custom place?
String tmp = System.getProperty(HOMEDIRSYSPROP, null);
if (tmp == null) {
// Nope!
return new File(FileSystemView.getFileSystemView().getDefaultDirectory(),
"Raccoon");
}
// User wants a custom directory, check if suitable.
File f = new File(tmp);
if (f.exists() && !f.isDirectory()) {
return new File(FileSystemView.getFileSystemView().getDefaultDirectory(),
"Raccoon");
}
else {
return f;
}
}
/**
* Sets the selected path based of the specified file. If this file is
* either <code>null</code> or not a directory, the home directory is
* selected.
*
* @param dir Points to a directory to be selected.
*/
public void setPath(File dir) {
final FileSystemView fsv = FileSystemView.getFileSystemView();
if ((dir == null) || !dir.isDirectory()) {
dir = fsv.getHomeDirectory();
}
ArrayList<BreadcrumbItem<File>> path = new ArrayList<>();
File parent = dir;
BreadcrumbItem<File> bci = new BreadcrumbItem<>(fsv.getSystemDisplayName(dir), dir);
bci.setIcon(fsv.getSystemIcon(dir));
path.add(bci);
while (true) {
parent = fsv.getParentDirectory(parent);
if (parent == null) {
break;
}
bci = new BreadcrumbItem<>(fsv.getSystemDisplayName(parent), parent);
bci.setIcon(fsv.getSystemIcon(parent));
path.add(bci);
}
Collections.reverse(path);
this.setPath(path);
}
public static void main(String[] args) {
File dir = FileSystemView.getFileSystemView().getDefaultDirectory();
printDirContent(dir);
System.setSecurityManager(new SecurityManager());
// The next test cases use 'dir' obtained without SecurityManager
try {
printDirContent(dir);
throw new RuntimeException("Dir content was derived bypass SecurityManager");
} catch (AccessControlException e) {
// It's a successful situation
}
}
public static void main(String[] args) {
File dir = FileSystemView.getFileSystemView().getDefaultDirectory();
printDirContent(dir);
System.setSecurityManager(new SecurityManager());
// The next test cases use 'dir' obtained without SecurityManager
try {
printDirContent(dir);
throw new RuntimeException("Dir content was derived bypass SecurityManager");
} catch (AccessControlException e) {
// It's a successful situation
}
}
private String getDeviceName(final String rootPath) {
final File f = new File(rootPath);
final FileSystemView v = FileSystemView.getFileSystemView();
String name = v.getSystemDisplayName(f);
if (name != null) {
int idx = name.lastIndexOf('(');
if (idx != -1) {
name = name.substring(0, idx);
}
name = name.trim();
if (name.isEmpty()) {
name = null;
}
}
return name;
}
/** ������ݷ�ʽ */
private void createShortcut() {
// ��ȡϵͳ����·��
String desktop = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
// ����ִ���ļ�·��
String appPath = System.getProperty("user.dir");
File exePath = new File(appPath).getParentFile();
JShellLink link = new JShellLink();
link.setFolder(desktop);
link.setName("Notebook.exe");
link.setPath(exePath.getAbsolutePath() + File.separator + "Notebook.exe");
// link.setArguments("form");
link.save();
System.out.println("======== create success ========");
}
static Image getImageSWT(File file) {
ImageIcon systemIcon = (ImageIcon) FileSystemView.getFileSystemView().getSystemIcon(file);
if (systemIcon == null) // Happens when file does not exist
return null;
java.awt.Image image = systemIcon.getImage();
if (image instanceof BufferedImage) {
return new Image(Display.getDefault(), convertToSWT((BufferedImage)image));
}
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return new Image(Display.getDefault(), convertToSWT(bufferedImage));
}
public static void main(String[] args) {
File dir = FileSystemView.getFileSystemView().getDefaultDirectory();
printDirContent(dir);
System.setSecurityManager(new SecurityManager());
// The next test cases use 'dir' obtained without SecurityManager
try {
printDirContent(dir);
throw new RuntimeException("Dir content was derived bypass SecurityManager");
} catch (AccessControlException e) {
// It's a successful situation
}
}
public void testNormalizeDrivesOnWindows48681 () {
if ((Utilities.isWindows () || (Utilities.getOperatingSystem () == Utilities.OS_OS2))) {
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
File file = roots[i];
if (FileSystemView.getFileSystemView().isFloppyDrive(file) || !file.exists()) {
continue;
}
File normalizedFile = FileUtil.normalizeFile(file);
File normalizedFile2 = FileUtil.normalizeFile(new File (file, "."));
assertEquals (normalizedFile.getPath(), normalizedFile2.getPath());
}
}
}
/**
* Get the default documents folder of the current user.
*
* @return The default documents folder of the current user, or the user's
* home directory if a documents folder could not be determined.
*/
public static File getDocumentsFolder() {
if (XDG.XDG_DOCUMENTS_DIR_FILE != null) {
// Should cover most Linuxes
return XDG.XDG_DOCUMENTS_DIR_FILE;
}
if (SystemUtils.isWindows()) {
// Should cover Windows
return FileSystemView.getFileSystemView().getDefaultDirectory();
}
File homeDir = new File(System.getProperty("user.home"));
File potentialDocsDir = new File(homeDir, "Documents");
if (potentialDocsDir.isDirectory()) {
// Should cover Mac OS X, and possibly others we missed
return potentialDocsDir;
}
return homeDir;
}
public static void main(String[] args) {
File dir = FileSystemView.getFileSystemView().getDefaultDirectory();
printDirContent(dir);
System.setSecurityManager(new SecurityManager());
// The next test cases use 'dir' obtained without SecurityManager
try {
printDirContent(dir);
throw new RuntimeException("Dir content was derived bypass SecurityManager");
} catch (AccessControlException e) {
// It's a successful situation
}
}
@Override
public void loggedActionPerformed(ActionEvent e) {
if (UIManager.getBoolean("FileChooser.readOnly")) {
return;
}
JFileChooser fc = getFileChooser();
File currentDirectory = fc.getCurrentDirectory();
FileSystemView fsv = fc.getFileSystemView();
File newFolder = null;
String name = SwingTools.showInputDialog("file_chooser.new_folder", "");
// abort if cancelled or user entered nothing
if (name == null || name.isEmpty()) {
return;
}
try {
newFolder = fsv.createNewFolder(currentDirectory);
if (newFolder.renameTo(fsv.createFileObject(fsv.getParentDirectory(newFolder), name))) {
newFolder = fsv.createFileObject(fsv.getParentDirectory(newFolder), name);
} else {
SwingTools.showVerySimpleErrorMessage("file_chooser.new_folder.rename", name);
}
} catch (IOException exc) {
SwingTools.showVerySimpleErrorMessage("file_chooser.new_folder.create", name);
return;
} catch (Exception exp) {
// do nothing
}
if (fc.isMultiSelectionEnabled()) {
fc.setSelectedFiles(new File[] { newFolder });
} else {
fc.setSelectedFile(newFolder);
}
fc.rescanCurrentDirectory();
}
@Override
public void updateUI ( @NotNull final C component )
{
// Removing all files filter
if ( component.isAcceptAllFileFilterUsed () )
{
component.removeChoosableFileFilter ( component.getAcceptAllFileFilter () );
}
// Update file view as file chooser was probably deserialized
if ( component.getFileSystemView () == null )
{
component.setFileSystemView ( FileSystemView.getFileSystemView () );
}
// Updating component UI
super.updateUI ( component );
// Updating UI file view for this file chooser
final FileView fileView = component.getUI ().getFileView ( component );
ReflectUtils.setFieldValueSafely ( component, "uiFileView", fileView );
// Adding all files filter
if ( component.isAcceptAllFileFilterUsed () )
{
component.addChoosableFileFilter ( component.getAcceptAllFileFilter () );
}
}
/**
* Returns true if specified FileChooser should use ShellFolder
*
* @param chooser the chooser
* @return the boolean
*/
public static boolean usesShellFolder(final JFileChooser chooser) {
Boolean prop = (Boolean) chooser.getClientProperty("FileChooser.useShellFolder");
return prop == null ? chooser.getFileSystemView().equals(FileSystemView.getFileSystemView())
: prop;
}
/**
* @功能:获取磁盘信息
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap<>();
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
/**
* The user directory. On Mac and Linux this should be the user home directory. On Windows platforms this
* is the "My Documents" directory.
*/
public static synchronized File getUserDirectory() {
if (USER_DIRECTORY == null) {
System.out.print("Fetching user directory... ");
USER_DIRECTORY = FileSystemView.getFileSystemView().getDefaultDirectory();
//Mostly for testing, in some environments USER_DIRECTORY can be null
if (USER_DIRECTORY == null) {
USER_DIRECTORY = getUserHome();
}
}
return USER_DIRECTORY;
}
private static void checkDefaultDirectory() {
if (System.getSecurityManager() == null) {
throw new RuntimeException("Security manager is not set!");
}
File defaultDirectory = FileSystemView.getFileSystemView().
getDefaultDirectory();
if (defaultDirectory != null) {
throw new RuntimeException("File system default directory is null!");
}
}
public static void main(String[] args) {
System.setSecurityManager(new SecurityManager());
// The next line of code forces FileSystemView to request data from Win32ShellFolder2,
// what causes an exception if a security manager installed (see the bug 6570445 description)
FileSystemView.getFileSystemView().getRoots();
System.out.println("Passed.");
}
/**
* 实时磁盘监控
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap<>();
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", fs[i].getFreeSpace()*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
public static void main(String[] args) {
System.setSecurityManager(new SecurityManager());
// The next line of code forces FileSystemView to request data from Win32ShellFolder2,
// what causes an exception if a security manager installed (see the bug 6570445 description)
FileSystemView.getFileSystemView().getRoots();
System.out.println("Passed.");
}
/**
* 实时磁盘监控
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap<>();
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", fs[i].getFreeSpace()*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
/**
* @功能:获取磁盘信息
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap<>();
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
private static void checkDefaultDirectory() {
if (System.getSecurityManager() == null) {
throw new RuntimeException("Security manager is not set!");
}
File defaultDirectory = FileSystemView.getFileSystemView().
getDefaultDirectory();
if (defaultDirectory != null) {
throw new RuntimeException("File system default directory is null!");
}
}
public GedEntry(File f,Class<T> classe) throws IOException {
this.classe=classe;
setName(Files.getNameWithoutExtension(f.getName()));
setExt(Files.getFileExtension(f.getName()));
setContent(Files.toByteArray(f));
setIsImage(ImageTools.isImage(f));
setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
setId(FileTools.checksum(f));
}
protected void loadChildren() {
FileSystemView fsv = (FileSystemView)getUserObject();
File[] roots = fsv.getRoots();
if (roots != null) {
Arrays.sort(roots);
for (int i = 0, c = roots.length; i < c; i++) {
add(new FileTreeNode(roots[i]));
}
}
}
private static void checkDefaultDirectory() {
if (System.getSecurityManager() == null) {
throw new RuntimeException("Security manager is not set!");
}
File defaultDirectory = FileSystemView.getFileSystemView().
getDefaultDirectory();
if (defaultDirectory != null) {
throw new RuntimeException("File system default directory is null!");
}
}