Java-I/O学习(4)

Java-I/O学习(4)

File

Java IO 的File类可以帮助你访问底层的文件系统,使用File类你可以:

  • 查看文件或目录是否存在

  • 如果目录不存在,可以创建

  • 读取文件的长度

  • 删除或移动文件

  • 删除文件

  • 查看路径指向的事文件还是目录

  • 读取目录下的文件列表

创建



// Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
File​(String pathname)

// Creates a new File instance from a parent pathname string and a child pathname string.
File​(String parent,String child)

// Creates a new File instance from a parent abstract pathname and a child pathname string.
File​(File parent,String child)

// Creates a new File instance by converting the given file: URI into an abstract pathname.
File​(URI uri)

获取文件信息的方法


// Tests whether the application can execute the file denoted by this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to execute files that are not marked executable. Consequently this method may return true even though the file does not have execute permissions.
boolean canExecute()

//Tests whether the application can read the file denoted by this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to read files that are marked as unreadable. Consequently this method may return true even though the file does not have read permissions.
boolean canRead()

//Tests whether the application can modify the file denoted by this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to modify files that are marked read-only. Consequently this method may return true even though the file is marked read-only.
boolean canWrite()

//Tests whether the file or directory denoted by this abstract pathname exists.
boolean exists()


//Tests whether this abstract pathname is absolute. The definition of absolute pathname is system dependent. On UNIX systems, a pathname is absolute if its prefix is "/". On Microsoft Windows systems, a pathname is absolute if its prefix is a drive specifier followed by "\\", or if its prefix is "\\\\".
boolean isAbsolute()

//Tests whether the file denoted by this abstract pathname is a directory.Where it is required to distinguish an I/O exception from the case that the file is not a directory, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.
boolean  isDirectory()

//Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.Where it is required to distinguish an I/O exception from the case that the file is not a normal file, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.
boolean isFile()


//Tests whether the file named by this abstract pathname is a hidden file. The exact definition of hidden is system-dependent. On UNIX systems, a file is considered to be hidden if its name begins with a period character ('.'). On Microsoft Windows systems, a file is considered to be hidden if it has been marked as such in the filesystem.
boolean isHidden()

//Returns the absolute form of this abstract pathname. Equivalent to new File(this.getAbsolutePath()).
File getAbsoluteFile()


//Returns the canonical pathname string of this abstract pathname.
String getCanonicalPath()

//Returns the canonical form of this abstract pathname. Equivalent to new File(this.getCanonicalPath()).
File getCanonicalFile()

//Returns the absolute pathname string of this abstract pathname.
String getAbsolutePath()


//Returns the number of unallocated bytes in the partition named by this abstract path name.
long getFreeSpace()

///Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().
long getUsableSpace()

//Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence. If the pathname's name sequence is empty, then the empty string is returned.
String getName()

//Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
String getParent()

//Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
File getParentFile()

//Converts this abstract pathname into a pathname string. The resulting string uses the default name-separator character to separate the names in the name sequence.
String getPath()

// Returns the size of the partition named by this abstract pathname.
long getTotalSpace()

使用:


    public static void main(String[] args) throws IOException {

        String pathName = "E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\d.txt";

        File file = new File(pathName);

        System.out.println("exists ? \n");
        System.out.println(file.exists());

        System.out.println("----------------------------------------------------------");

//        System.out.println(file.length());

        System.out.println("canExecute ? \n");
        System.out.println(file.canExecute());

        System.out.println("----------------------------------------------------------");

        System.out.println("canRead ? \n");
        System.out.println(file.canRead());

        System.out.println("----------------------------------------------------------");

        System.out.println("canWrite ? \n");
        System.out.println(file.canWrite());

        System.out.println("----------------------------------------------------------");

        System.out.println("isFile ? \n");
        System.out.println(file.isFile());

        System.out.println("----------------------------------------------------------");

        System.out.println("isDirectory ? \n");
        System.out.println(file.isDirectory());

        System.out.println("----------------------------------------------------------");

        System.out.println("isAbsolute ? \n");
        System.out.println(file.isAbsolute());

        System.out.println("----------------------------------------------------------");

        System.out.println("isHidden ? \n");
        System.out.println(file.isHidden());

        System.out.println("----------------------------------------------------------");

        System.out.println("getName  \n");
        System.out.println(file.getName());

        System.out.println("----------------------------------------------------------");

        System.out.println("getUsableSpace  \n");
        System.out.println(file.getUsableSpace());

        System.out.println("----------------------------------------------------------");

        System.out.println("getTotalSpace  \n");
        System.out.println(file.getTotalSpace());

        System.out.println("----------------------------------------------------------");

        System.out.println("getPath  \n");
        System.out.println(file.getPath());

        System.out.println("----------------------------------------------------------");


        System.out.println("getParentFile  \n");
        System.out.println(file.getParentFile());

        System.out.println("----------------------------------------------------------");


        System.out.println("getParent  \n");
        System.out.println(file.getParent());

        System.out.println("----------------------------------------------------------");

        System.out.println("getFreeSpace  \n");
        System.out.println(file.getFreeSpace());

        System.out.println("----------------------------------------------------------");

        System.out.println("getCanonicalPath  \n");
        System.out.println(file.getCanonicalPath());

        System.out.println("----------------------------------------------------------");


        System.out.println("getCanonicalFile  \n");
        System.out.println(file.getCanonicalFile());

        System.out.println("----------------------------------------------------------");
        
    }

创建新文件




// Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
// Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
boolean createNewFile()


//reates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null).The Files.createTempFile method provides an alternative method to create an empty file in the temporary-file directory. Files created by that method may have more restrictive access permissions to files created by this method and so may be more suited to security-sensitive applications.

//prefix - The prefix string to be used in generating the file's name; must be at least three characters long

//suffix - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used
static File createTempFile​(String prefix,String suffix)

//Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:

//1  The file denoted by the returned abstract pathname did not exist before this method was invoked, and
//2  Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.

//prefix - The prefix string to be used in generating the file's name; must be at least three characters long

//suffix - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used

//directory - The directory in which the file is to be created, or null if the default temporary-file directory is to be used
static File createTempFile​(String prefix,String suffix,File directory)



  public static void main(String[] args) throws IOException {

        String pathName = "E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\op.txt";

        File file = new File(pathName);

        System.out.println("创建新文件\n");
        System.out.println(file.createNewFile());

        System.out.println("--------------");

        String prefix = "etcedk";

        String suffix = ".txt";


        File file2 = File.createTempFile(prefix,suffix);

        System.out.println(file2.getName());

        System.out.println(file2.getAbsolutePath());


    }

针对读写权限

//A convenience method to set the owner's execute permission for this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to execute files that are not marked executable.

//executable - If true, sets the access permission to allow execute operations; if false to disallow execute operations
boolean setExecutable​(boolean executable)

//Sets the owner's or everybody's execute permission for this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to execute files that are not marked executable.
//The Files class defines methods that operate on file attributes including file permissions. This may be used when finer manipulation of file permissions is required.

//executable - If true, sets the access permission to allow execute operations; if false to disallow execute operations

//ownerOnly - If true, the execute permission applies only to the owner's execute permission; otherwise, it applies to everybody. If the underlying file system can not distinguish the owner's execute permission from that of others, then the permission will apply to everybody, regardless of this value.
boolean setExecutable​(boolean executable,boolean ownerOnly)

//Sets the last-modified time of the file or directory named by this abstract pathname.
//All platforms support file-modification times to the nearest second, but some provide more precision. The argument will be truncated to fit the supported precision. If the operation succeeds and no intervening operations on the file take place, then the next invocation of the lastModified() method will return the (possibly truncated) time argument that was passed to this method.

//time - The new last-modified time, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)
boolean setLastModified​(long time)

//Marks the file or directory named by this abstract pathname so that only read operations are allowed. After invoking this method the file or directory will not change until it is either deleted or marked to allow write access. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to modify files that are marked read-only. Whether or not a read-only file or directory may be deleted depends upon the underlying system.
boolean setReadOnly()

//Sets the owner's or everybody's write permission for this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to modify files that disallow write operations.The Files class defines methods that operate on file attributes including file permissions. This may be used when finer manipulation of file permissions is required.

//writable - If true, sets the access permission to allow write operations; if false to disallow write operations

//ownerOnly - If true, the write permission applies only to the owner's write permission; otherwise, it applies to everybody. If the underlying file system can not distinguish the owner's write permission from that of others, then the permission will apply to everybody, regardless of this value.
boolean setWritable​(boolean writable,boolean ownerOnly)

//A convenience method to set the owner's write permission for this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to modify files that disallow write operations.
boolean setWritable​(boolean writable)

//Sets the owner's or everybody's read permission for this abstract pathname. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to read files that are marked as unreadable.

//readable - If true, sets the access permission to allow read operations; if false to disallow read operations

//ownerOnly - If true, the read permission applies only to the owner's read permission; otherwise, it applies to everybody. If the underlying file system can not distinguish the owner's read permission from that of others, then the permission will apply to everybody, regardless of this value.
boolean setReadable​(boolean readable,boolean ownerOnly)

list


//Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

//If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of strings is returned, one for each file or directory in the directory. Names denoting the directory itself and the directory's parent directory are not included in the result. Each string is a file name rather than a complete path.

//There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

//Note that the Files class defines the newDirectoryStream method to open a directory and iterate over the names of the files in the directory. This may use less resources when working with very large directories, and may be more responsive when working with remote directories.
String[] list()



//Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
//If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using the File(File, String) constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.

//There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

//Note that the Files class defines the newDirectoryStream method to open a directory and iterate over the names of the files in the directory. This may use less resources when working with very large directories.
File[] listFiles()

使用


  public static void main(String[] args) {

        String pathName = "E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO";

        File file = new File(pathName);
        for (String s : file.list()) {

            System.out.println(s);

        }

        System.out.println("-------------------------------------------------");

        
        for (File f : file.listFiles()) {

            System.out.println(f.getAbsolutePath());
        }


    }

针对目录


//Creates the directory named by this abstract pathname.

//true if and only if the directory was created; false otherwise
boolean mkdir()

//Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

//true if and only if the directory was created, along with all necessary parent directories; false otherwise
boolean mkdirs()

使用:



 public static void main(String[] args) {

        String pathName = "E:\\learn-java\\Learning-Java\\MyNotes\\better_write\\Java_IO\\IG";

        File file = new File(pathName);

        System.out.println("创建目录 : \n");

        System.out.println(file.mkdir());


    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值