11.4
package qimoxiangmu; import javax.swing.*; import java.io.*; public class ChooseFile { public static void main(String[] args) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY ); //显示打开文件对话框 int result = fileChooser.showOpenDialog( null ); // user clicked Cancel button on dialog if ( result == JFileChooser.CANCEL_OPTION ) return; File fileName = fileChooser.getSelectedFile(); System.out.println("您选择了:" + fileName.getName()); } }
运行结果如下:
您选择了:9. 山花绽放.lnk
package qimoxiangmu; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; public class FileFinder extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path name=file.getFileName(); System.out.println("Examining "+name); if(matcher.matches(name)){ foundPaths.add(file); } return FileVisitResult.CONTINUE; } private PathMatcher matcher; public ArrayList<Path> foundPaths=new ArrayList<>(); public FileFinder(String pattern){ matcher=FileSystems.getDefault().getPathMatcher("glob:"+pattern); } public static void main(String[] args) { Path fileDir=Paths.get("D:\\test"); FileFinder finder=new FileFinder("*.java"); try { Files.walkFileTree(fileDir, finder); ArrayList<Path> foundFiles=finder.foundPaths; if(foundFiles.size()>0){ for (Path path : foundFiles) { System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS)); } } else { System.out.println("No files were found!"); } } catch (IOException e) { e.printStackTrace(); } } }
运行结果如下:
No files were found!
package qimoxiangmu; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.List; public class FilesTest { public static void main(String[] args) { // copy file Path source = Paths.get("D:/Temp/line1.bmp"); Path target = Paths.get("D:/Temp/backup.bmp"); try { Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { ex.printStackTrace(); } Path source2 = Paths.get("D:/Temp/backup.bmp"); Path target2 = Paths.get("D:/123data/backup2.bmp"); try { Files.move(source2, target2, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { ex.printStackTrace(); } // write and read to a text file Path textFile = Paths.get("D:/Temp/speech.txt"); Charset charset = Charset.forName("US-ASCII"); String line1 = "Easy read and write"; String line2 = "with java.nio.file.Files"; List<String> lines = Arrays.asList(line1, line2); try { Files.write(textFile, lines, charset); } catch (IOException ex) { ex.printStackTrace(); } List<String> linesRead = null; try { // read back linesRead = Files.readAllLines(textFile, charset); } catch (IOException ex) { ex.printStackTrace(); } if (linesRead != null) { for (String line : linesRead) { System.out.println(line); } } } }
运行结果如下:
Easy read and write
with java.nio.file.Files
package qimoxiangmu; import java.io.*; import java.util.ArrayList; public class FileTest { public static void main(String[] args) throws IOException { File file = new File("c:\\windows"); if(file.isFile()) { // 是否为文件 System.out.println(" 文件"); System.out.print( file.canRead() ? "可读" : "不可读"); System.out.print( file.canWrite() ? "可写" : "不可写"); System.out.println( file.length() + "字节"); } else { // 列出所有的文件及目录 File[] files = file.listFiles(); ArrayList<File> fileList = new ArrayList<File>(); for(int i = 0; i < files.length; i++) { // 先列出目录 if(files[i].isDirectory()) { //是否为目录 // 取得路径名 System.out.println("[" + files[i].getPath() + "]"); } else { // 文件先存入fileList,待会再列出?? fileList.add(files[i]); } } // 列出文件 for(File f: fileList) { System.out.println(f.toString()); } System.out.println(); } //以当前路径来创建一个File对象 file = new File("."); //直接获取文件名,输出一点 System.out.println(file.getName()); //获取相对路径的父路径可能出错,下面代码输出null System.out.println(file.getParent()); //获取绝对路径 System.out.println(file.getAbsoluteFile()); //获取上一级路径 System.out.println(file.getAbsoluteFile().getParent()); //在当前路径下创建一个临时文件 File tmpFile = File.createTempFile("aaa", ".txt", file); //指定当JVM退出时删除该文件 tmpFile.deleteOnExit(); //以系统当前时间作为新文件名来创建新文件 File newFile = new File(System.currentTimeMillis() + ""); System.out.println("newFile对象是否存在:" + newFile.exists()); //以指定newFile对象来创建一个文件 newFile.createNewFile(); //以newFile对象来创建一个目录,因为newFile已经存在, //所以下面方法返回false,即无法创建该目录 newFile.mkdir(); //使用list方法来列出当前路径下的所有文件和路径 String[] fileList = file.list(); System.out.println("======当前路径下所有文件和路径如下====="); for (String fileName : fileList) { System.out.println(fileName); } //listRoots静态方法列出所有的磁盘根路径。 File[] roots = File.listRoots(); System.out.println("======系统所有根路径如下====="); for (File root : roots) { System.out.println(root); } } }
运行结果如下:
[c:\windows\addins]
[c:\windows\appcompat]
[c:\windows\apppatch]
[c:\windows\AppReadiness]
[c:\windows\assembly]
[c:\windows\bcastdvr]
[c:\windows\Boot]
[c:\windows\Branding]
[c:\windows\CbsTemp]
[c:\windows\Containers]
[c:\windows\Cursors]
[c:\windows\debug]
[c:\windows\Defender]
[c:\windows\diagnostics]
[c:\windows\DiagTrack]
[c:\windows\DigitalLocker]
[c:\windows\Downloaded Program Files]
[c:\windows\ELAMBKUP]
[c:\windows\en-US]
[c:\windows\Favicon_ICON]
[c:\windows\Fonts]
[c:\windows\GameBarPresenceWriter]
[c:\windows\Globalization]
[c:\windows\Help]
[c:\windows\IdentityCRL]
[c:\windows\IME]
[c:\windows\ImmersiveControlPanel]
[c:\windows\INF]
[c:\windows\InputMethod]
[c:\windows\Installer]
[c:\windows\java]
[c:\windows\L2Schemas]
[c:\windows\LanguageOverlayCache]
[c:\windows\Lenovo]
[c:\windows\LiveKernelReports]
[c:\windows\Logs]
[c:\windows\Media]
[c:\windows\Microsoft.NET]
[c:\windows\Migration]
[c:\windows\minidump]
[c:\windows\ModemLogs]
[c:\windows\Netease]
[c:\windows\OCR]
[c:\windows\Offline Web Pages]
[c:\windows\panther]
[c:\windows\PCHEALTH]
[c:\windows\Performance]
[c:\windows\PLA]
[c:\windows\PolicyDefinitions]
[c:\windows\Prefetch]
[c:\windows\PrintDialog]
[c:\windows\Provisioning]
[c:\windows\Registration]
[c:\windows\rescache]
[c:\windows\Resources]
[c:\windows\SchCache]
[c:\windows\schemas]
[c:\windows\security]
[c:\windows\ServiceProfiles]
[c:\windows\ServiceState]
[c:\windows\servicing]
[c:\windows\Setup]
[c:\windows\ShellComponents]
[c:\windows\ShellExperiences]
[c:\windows\SKB]
[c:\windows\SoftwareDistribution]
[c:\windows\Speech]
[c:\windows\Speech_OneCore]
[c:\windows\symbols]
[c:\windows\System]
[c:\windows\System32]
[c:\windows\SystemApps]
[c:\windows\SystemResources]
[c:\windows\SysWOW64]
[c:\windows\TAPI]
[c:\windows\Tasks]
[c:\windows\Temp]
[c:\windows\TextInput]
[c:\windows\tracing]
[c:\windows\twain_32]
[c:\windows\Vss]
[c:\windows\WaaS]
[c:\windows\Web]
[c:\windows\WinSxS]
[c:\windows\zh-CN]
c:\windows\acct.txt
c:\windows\area.txt
c:\windows\authsel.txt
c:\windows\AvsOpt.txt
c:\windows\a_domain.txt
c:\windows\bfsvc.exe
c:\windows\bootstat.dat
c:\windows\CNI.TAG
c:\windows\core.ver
c:\windows\CoreCountrySpecific.xml
c:\windows\csup.txt
c:\windows\diagerr.xml
c:\windows\diagwrn.xml
c:\windows\DirectX.log
c:\windows\eap.txt
c:\windows\eapkeep.txt
c:\windows\edu_look.bmp
c:\windows\explorer.exe
c:\windows\guest.txt
c:\windows\HelpPane.exe
c:\windows\hh.exe
c:\windows\info.txt
c:\windows\language.txt
c:\windows\machineinfo.sav
c:\windows\MFGSTAT.zip
c:\windows\mib.bin
c:\windows\msginfosize.txt
c:\windows\notepad.exe
c:\windows\NvContainerRecovery.bat
c:\windows\NvTelemetryContainerRecovery.bat
c:\windows\ODBC.INI
c:\windows\PFRO.log
c:\windows\PLDDATA.XML
c:\windows\ProductInfo.ini
c:\windows\regedit.exe
c:\windows\setupact.log
c:\windows\setuperr.log
c:\windows\splwow64.exe
c:\windows\system.ini
c:\windows\twain_32.dll
c:\windows\vbaddin.ini
c:\windows\win.ini
c:\windows\WindowsShell.Manifest
c:\windows\WindowsUpdate.log
c:\windows\winhlp32.exe
c:\windows\WMSysPr9.prx
c:\windows\write.exe
.
null
D:\JAVA\新建文件夹\qimoxiangmu\.
D:\JAVA\新建文件夹\qimoxiangmu
newFile对象是否存在:false
======当前路径下所有文件和路径如下=====
.classpath
.project
.settings
1608220060270
aaa5574514488376449911.txt
bin
src
======系统所有根路径如下=====
C:\
D:\
F:\
package qimoxiangmu; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class FileVisitorDemo extends SimpleFileVisitor<Path> { @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { System.out.println("Just visited "+dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { System.out.println("Aoout to visit "+dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if(attrs.isRegularFile()){ System.out.println("Regular File:"); } System.out.println(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { System.err.println(exc.getMessage()); return FileVisitResult.CONTINUE; } public static void main(String[] args) { Path fileDirPath=Paths.get("D:\\test"); FileVisitorDemo visitor=new FileVisitorDemo(); try { Files.walkFileTree(fileDirPath, visitor); } catch (IOException e) { e.printStackTrace(); } } }
运行结果如下:
D:\test
package qimoxiangmu; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.HashMap; import java.util.Map; public class FileWatcherDemo { /** * @param args */ public static void main(String[] args) { //创建一个WatchService对象,此对象将用于管理特定文件夹的变动信息队列。 try(WatchService service=FileSystems.getDefault().newWatchService()) { //此集合可保存多个文件夹的监控信息,当前只使用了一个 Map<WatchKey, Path> keyMap=new HashMap<>(); Path path=Paths.get("D:\\test"); //设置WatchService对象管理的内部队列,将保存指定的文件夹的创建、删除和修改事件信息 //返回的WatchKey对象可用于从事件队列中获取事件对象 WatchKey key=path.register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY); keyMap.put(key, path); do { //开始监控,阻塞等待,当感兴趣的事件发生时,take()方法返回。 key=service.take(); Path eventDir=keyMap.get(key); //从事件队列中提取所有的事件 for (WatchEvent<?> event : key.pollEvents()) { //是什么类型的事件? WatchEvent.Kind<?> kind=event.kind(); //是哪个对象发生了变动? Path eventPath=(Path)event.context(); System.out.println(eventDir+":"+kind+":"+eventPath); } } while (key.reset()); //reset方法重置此对象,让其可以重新接收信息 } catch (Exception e) { } } }
package qimoxiangmu; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class PathTest { public static void main(String[] args) { FileSystem fileSystem=FileSystems.getDefault(); Path examplePath=fileSystem.getPath("c:/windows"); System.out.println(examplePath.toString()); Path path = Paths.get("D:/Temp/pathTest.txt"); System.out.println("path name count:" + path.getNameCount()); System.out.println(path.getName(0)); System.out.println(path.getName(1)); System.out.println("filename: " + path.getFileName()); System.out.println("parent: " + path.getParent()); Path parent = path.getParent(); System.out.println("parent: " + parent.getParent().getParent()); try { Files.deleteIfExists(path); Files.createFile(path); } catch (IOException ex) { ex.printStackTrace(); } Path newDir = Paths.get("D:/Temp/newDir"); try { if (Files.notExists(path)) { Files.createDirectory(newDir); } System.out.println("isDirectory: " + Files.isDirectory(newDir)); System.out.println("size : " + Files.size(newDir)); } catch (IOException ex) { ex.printStackTrace(); } System.out.println("DONE"); } }
运行结果如下:
c:\windows
path name count:2
Temp
pathTest.txt
filename: pathTest.txt
parent: D:\Temp
parent: null
isDirectory: true
size : 0
DONE