Files.isSameFile-記得要try catch
比較2個Path是否相同的檔案或目錄
需注意重點有
1 當兩個PATH名稱一樣但無真實檔案時,並不會檢查檔案是否存在,回傳會是True如下
Path path1 = Paths.get("C:", "AAA","howard","testk.txt");
Path path2 = Paths.get("C:", "AAA","howard","testk.txt");
System.out.println(Files.isSameFile(path1, path2));
testk.txt 並不存在於C:\AAA\howard\testk.txt
2 當兩個PATH
路徑不一樣時會檢查檔案是否存在,如不存在會拋出java.nio.file.NoSuchFileException
3 文件上說此方法會預設會先呼叫
checkRead 如果沒有讀取權限會拋出SecurityException
4 如果檔案是symbolic links 則會看兩個檔案是否有相關!依相關回傳True或false
Files.delete And deleteIfExists
delete特性為:
1 刪除的資料為目錄時記得,目錄內不可有檔案存在不然會拋出java.nio.file.DirectoryNotEmptyException
2 當指定刪除的Path不存在時會拋出java.nio.file.NoSuchFileException,使用deleteIfExists就不會拋出Exception~
3 檔案如果是Link不會刪除實體只刪除連接
createDirectory-->不能建立多個子目錄
在不能使用permissions環境會拋出錯誤
'posix:permissions' not supported as initial attribute
當無法建立資料夾或資料夾已存在會拋出錯誤
FileAlreadyExistsException - if a directory could not otherwise be created because a file of that name already exists (optional specific exception)
createDirectories-->可以建立子目錄
當存在的檔案不是資料夾時會拋出錯誤
exceptions such as FileAlreadyExistsException
or UnsupportedOperationException (e.g., when the
file attributes cannot be set as given by dirAttrs).
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rwxr-x---");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(file, attr);
Files.createTempDirectory差異
try {
Path path = Files.createTempDirectory("Howard");
Path pathX = Files.createTempDirectory(path2,"Howard");
System.out.println(path);
System.out.println(pathX);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
呼叫createTempDirectory沒有Path參數的他會幫你寫入系統Temp目錄,如有帶Path的就不建立
C:\Users\howard\AppData\Local\Temp\Howard1238750409634903782
C:\AAA\howard\Howard7680292432452175988
Files.createSymbolicLink(path2, target)
Path path2 = Paths.get("C:"+"\\AAA\\howard\\Test1.java");
Path target = Paths.get("C:"+"\\AAA\\howard\\test9.txt");
Path pathSymbo = Files.createSymbolicLink(path2, target);
System.out.println(pathSymbo);
最後顯示出建立Symbolic的檔名為"Test1.java"而不是"test9.txt"
Files.getPosixFilePermissions
在沒有建立全限的環境之下會出使用以上方法會產生
java.lang.
UnsupportedOperationException
Files.readSymbolicLink(source)
Files.readSymbolicLink(source) 會讀取Link的來源目錄
如source不是link會拋出java.nio.file.NotLinkException
讀取Attributes
readAttributes
修改Attribute與讀取可用
getFileAttributeView
EX:
BasicFileAttributeView basView = Files.getFileAttributeView(newFile, BasicFileAttributeView.class);//不會拋出IOException
注意不要跟Files.readAttributes()搞混了
相關AttributeView類別如下
BasicFileAttributeView – Provides a view of basic attributes that are required to be supported by all file system implementations.
DosFileAttributeView – Extends the basic attribute view with the standard four bits supported on file systems that support the DOS attributes.
PosixFileAttributeView – Extends the basic attribute view with attributes supported on file systems that support the POSIX family of standards, such as UNIX. These attributes include file owner, group owner, and the nine related access permissions.
FileOwnerAttributeView – Supported by any file system implementation that supports the concept of a file owner.
AclFileAttributeView – Supports reading or updating a file's Access Control Lists (ACL). The NFSv4 ACL model is supported. Any ACL model, such as the Windows ACL model, that has a well-defined mapping to the NFSv4 model might also be supported.
UserDefinedFileAttributeView – Enables support of metadata that is user defined. This view can be mapped to any extension mechanisms that a system supports. In the Solaris OS, for example, you can use this view to store the MIME type of a file.
UserPrincipalLookupService
可提供GroupPrincipal與UserPrincipal
擁有以上2物件就可修改檔案的群組或擁有者
修改方法如下:
Path file = ...;
GroupPrincipal group =
file.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByGroupName("green");
也可以由
FileSystems.getDefault().getUserPrincipalLookupService();
Ex:
FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName(name)
取得UserPrincipalLookupService
Files.getFileAttributeView(file, PosixFileAttributeView.class)
.setGroup(group);
如傳入的group name 或 owner名稱找不到會拋出UserPrincipalNotFoundException
PosixFilePermissions幫助設定權限
The PosixFilePermissions helper class provides several useful methods, as follows:
- The
toString method, used in the previous code snippet, converts the file permissions to a string (for example, rw-r--r--).
- The
fromString method accepts a string representing the file permissions and constructs a Set of file permissions.
- The
asFileAttribute method accepts a Set of file permissions and constructs a file attribute that can be passed to thePath.createFile or Path.createDirectory method.
The following code snippet reads the attributes from one file and creates a new file, assigning the attributes from the original file to the new file:
Path sourceFile = ...;
Path newFile = ...;
PosixFileAttributes attrs =
Files.readAttributes(sourceFile, PosixFileAttributes.class);
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(attrs.permissions());
Files.createFile(file, attr);
The
asFileAttribute method wraps the permissions as a
FileAttribute. The code then attempts to create a new file with those permissions. Note that the
umask also applies, so the new file might be more secure than the permissions that were requested.
To set a file's permissions to values represented as a hard-coded string, you can use the following code:
Path file = ...;
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-------");
FileAttribute<Set<PosixFilePermission>> attr =
PosixFilePermissions.asFileAttribute(perms);
Files.setPosixFilePermissions(file, perms);
Files.createSymbolicLink
Files.createSymbolicLink(link, source,fattr);
建立時不可設定權限不然會拋出
Initial file attributesnot supported when creating symbolic link
Path.subpath如果長度不符合會拋
java.lang.IllegalArgumentException
Files.getAttribute
Files.getAttribute(path, "sized", LinkOption.NOFOLLOW_LINKS);
以上會拋出java.lang.IllegalArgumentException: ‘sized’ not recognized
Files.getAttribute(path, "dos:size", LinkOption.NOFOLLOW_LINKS);
Exception in thread "main" java.lang.UnsupportedOperationException: View 'dos' not available
If you do not specify the correct view name,you will get an UnsupportedOperationException,
List<String>Files.readAllLines(Path,Charset)
讀取一個文字檔,將毎一行放在一個List中
byte[] Files.readAllBytes(path)
newInputStream
Files.newInputStream(path1,
StandardOpenOption.CREATE)
以上會產生 java.lang.UnsupportedOperationException: 'CREATE' not allowed
錯誤
toRealPath
當指定路徑不存在會出現
java.nio.file.NoSuchFileException: /Users/user/tmp/JavaIo1lnX.java