Article From:

package filet; import; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class FileTest { public static void main(String[] args) throws Exception { //Copy fileFiles.copy (Paths.get ("C:\\Users\\Administrator\\Desktop\\a.txt")) and new FileOutputStream ("C:\\Us").Ers\\Administrator\\Desktop\\test.txt "))/ / get all the files of fileTest at one timeList< String> lines = FilEs.readAllLines (Paths.get ("C:\\Users\\Administrator\\Desktop\\a.txt"));System.out.println (lines);/ / copy fileFiles.copy (Paths.get ("C:\\Users\\Administrator\\Desktop\\dd.png")), new FileOutPutStream ("C:\\Users\\Administrator\\Desktop\\ddtest.png"));List< String> pome = NewArrayList< > ();Pome.add ("aadddd");Pome.add ("dfgfdf");/ / directly to write multiple string contents to the specified fileFileS.write (Paths.get ("C:\\Users\\Administrator\\Desktop\\a.txt"), pome);/ / / / use the java8 new Stream API to read the fileCapacityFiles.list (Paths.get (".")).ForEach (path-> System.out.println (path));Files.lines (PaThs.get ("C:\\Users\\Administrator\\Desktop\\a.txt")).ForEach (line-> System.out.println (line));/ / / / judge C disk available spaceFileStore csStore = Files.getFileStore (Paths.get ("C:"));System.out.println("C shared space:" +csStore.getTotalSpace ());System.out.println ("C available space:" +csStore.getUsableSpace ());}}

  Traversing files and directories with FileVisitor

package filet;

import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class FileVisitorTest {
    public static void main(String[] args) throws Exception {
        //Traversing all the files and subdirectories under the disk
        Files.walkFileTree(Paths.get("C:\\Users\\Administrator\\Desktop"), new     SimpleFileVisitor<Path>() {
            //The method is triggered when the file is accessed
            public FileVisitResult visitFile(Path file,BasicFileAttributes attrs) {
                System.out.println("The "+file+" file is being accessed. ");
                //Find the File
                if(file.endsWith("a.txt")) {
                    System.out.println("The target file has been found ");
                    return FileVisitResult.TERMINATE;
                return FileVisitResult.CONTINUE;
            //This method is triggered when you start access to the target directory
            public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs) {
                System.out.println("The "+dir+" path is being accessed.);
                return FileVisitResult.CONTINUE;



Link of this Article: Path; Paths and Files; FileVisitor

Leave a Reply

Your email address will not be published. Required fields are marked *