HTML/JavaScript小工具

HTML/JavaScript小工具

2013年12月24日 星期二

Vector 相減相加的涵義

加法涵義比較簡單
Vector1 + Vector2

我要往Vector2的方向前進 原本是2 往前走5步-- 2+5 7方向就正7
例如:子彈如果以想往某個Vector方向走就把它給加上

Vector1 - Vector2

減法可以先從 一般數來看
如果 8想變成10
會先10 - 8 = 2
在 8+ 2 就變成10嘍~~

也就是說如果我的A想移動到B去

我會先將C = B - A
然後在將A作加C

2013年12月23日 星期一

yield 2秒後再行動

    1. StartCoroutine(MyMethod());

  1. IEnumerator MyMethod() {
  2. Debug.Log("Before Waiting 2 seconds");
  3. yield return new WaitForSeconds(2);
  4. Debug.Log("After Waiting 2 Seconds")
  5. }
另外還有
WaitForFixedUpdate可以用
using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    IEnumerator Example() {
        yield return new WaitForFixedUpdate();
    }
}

Physics2D.Linecast

grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
以上程式碼是用來測試是否在地面上

指的是投射一條線!!可指定起始點與結束點
當碰到第一個Collider 會回傳一個 RaycastHit2D 
如果不想回傳RaycastHit2D可使用 LinecastNonAlloc

如果想投射多個Cllder可用Physics2D.LinecastAll 

2013年5月15日 星期三

Watching a Directory for Changes

簡介: 這是JDK 7低新功能主要ㄌㄟ對於資料夾監聽是否有刪除修改新增等等!!

需要NIO2的基礎優~~我的Blog有基礎的一些教學也可以去java看教學!
作法如下
1 先建立一個你要監聽的對象如我想監聽src資料夾可以這麼做


 Path path = Paths.get("..\\src");


2  建立一個WatchService,可由FileSystems.getDefault().newWatchService();取得建立時記得要try catch

3 將WatchService與需監聽的狀態 註冊到 Path上 程式碼如下
因為Path有實作Watchable介面才可註冊WatchService

try {
watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

4 建立一個無窮迴圈他取得資料夾修改資訊watchService有三種方式可以取得修改資訊
1 poll 會返回WatchKey,如果沒有值會回傳null
2 poll(timeout, unit) 可指定等待時間返回WatchKey
3 take 如序列中沒資料時會wait也返回WatchKey

5 透過WatchKey當中的pollEvents 使用For回圈取得所有註冊狀態的回應

6 最後記得需要呼叫WatchKey的rest 將狀態變成Ready,不然會收不到新的訊息
7 你的的程序中可能會收到一個OVERFLOW事件,甚至如果該程序被沒有針對此事件註冊。
8 如果你註冊在根目錄其子目錄並不會有監聽效果!

程式下載

補充:
可監聽的狀態有:

  • ENTRY_CREATE – A directory entry is created.
  • ENTRY_DELETE – A directory entry is deleted.
  • ENTRY_MODIFY – A directory entry is modified.
  • OVERFLOW – Indicates that events might have been lost or discarded. You do not have to register for the OVERFLOW event to receive it.

WatchKey的狀態
  • Ready indicates that the key is ready to accept events. When first created, a key is in the ready state.
  • path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,這時會回傳WatchKey,此時的狀態事Ready 
  • Signaled indicates that one or more events are queued. Once the key has been signaled, it is no longer in the ready state until the reset method is invoked.
  • WatchKey watchKey = watchService.take();透過watchService取的WatchKey因已經有Event在內的就變成了Signaled 
  • Invalid indicates that the key is no longer active. This state happens when one of the following events occurs:
    • The process explicitly cancels the key by using the cancel method.
    • The directory becomes inaccessible.
    • The watch service is closed.
    • 當呼叫 watchKey.reset()或是watchKey.isValid()都會回傳false
 You do not need to specify the OVERFLOW event while registering a watchable with a WatchService  to receive this event.

  The counts for ENTRY_CREATE and ENTRY_DELETE are always 1.
  This is as per the API description of these events. However, the count for  ENTRY_MODIFY and  OVERFLOW      can be 1 or greater.

 The count for ENTRY_MODIFY and  OVERFLOW  the count can be greater than 1.    可能會大於1      





2013年5月14日 星期二

Java_NIO2 Files copy and move


Files.copy(
sourcetarget, CopyOption...)

特性
預設如果target的檔名已存在,會拋出FileAlreadyExistsException2 預設狀況下Copy symbolic link 會copy原始檔案而不會 copy link檔
3 copy目錄並不會將目錄內的檔案一起copy!
4 CopyOption 設定成 StandardCopyOption.REPLACE_EXISTING
  a copy 檔案名稱相同時會覆蓋
  b copy目錄時target不是空目錄會拋出java.nio.file.DirectoryNotEmptyException
5 COPY_ATTRIBUTES 在copy時會將source的權限等資料一起copy除了 last-modified-time
NOFOLLOW_LINKS copy時會COPY link不copy資料來源!
7 如果source目錄不存在會顯示java.nio.file.NoSuchFileException
8 在copy的CopyOption中不可使用StandardCopyOption.ATOMIC_MOVE參數會產生錯誤java.lang.UnsupportedOperationException: Unsupported copy option


public static Path move(Path source,
        Path target,
        CopyOption... options)

大致與COPY雷同!
除了~
1 如果move是link移動的事link不是資料來源
2 move目錄會將內部的檔案一起移動
類似linux內的move行為

3 If Files.move(...) is called with StandardCopyOption.COPY_ATTRIBUTES anUnsupportedOperationException is thrown.

move VS copy


1 預設都不會覆蓋target檔案除非屬性設為REPLACE_EXISTING
2 move一個符號鏈接,鏈接本身會被移動,而不是目標文件。重要的是要注意,copy預設方法的情況下,如果指定一個符號鏈接,複製鏈接的目標,而不是鏈接本身
3move可移動有內容的資料夾,如果成功移動資料夾內容也被移動
4 move可指定ATOMIC_MOVE copy option 如未指定當按移動錯誤會產生未知的狀態!

move 與 copy語法跟我們在linux下有些不同
如:我想將/Users/user/tmp2 copy 或 move 到 /Users/user/tmp下可以這樣寫

cp  -r /Users/user/tmp2   /Users/user/tmp

但java程式中不可這樣寫

Path1 =  /Users/user/tmp2

Path2  = /Users/user/tmp

copy(Path1, Path2);
程式會認為你要將tmp覆蓋成tmp2而不是將tmp2放至於tmp目錄下正確寫法如下


Path1 =  /Users/user/tmp2

Path2  = /Users/user/tmp/tmp2
copy(Path1, Path2);





java_nio2_2_FILES_ getAttribute與readAttributes


Path path2 = Paths.get("/Users/user/tmp/JavaIo1ln.java");<===他是SymbolicLink檔
try {
BasicFileAttributes basicFileAttributes = Files.readAttributes(path2, BasicFileAttributes.class);
System.out.println(basicFileAttributes.isSymbolicLink());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

以上會顯示false,他預設會去取得SymbolicLink真實的資源!

如果屬性填寫錯誤會出現java.lang.IllegalArgumentException: 'sized' not recognized
如下例:
Map<String, Object> myMpa = Files.readAttributes(path2, "sized");
sized是錯誤的參數

getAttribute

Files.getAttribute(path, "creationTime",LinkOption.NOFOLLOW_LINKS);

參數部分
1 要查詢屬性的Path
2 使用 [view-name:]attribute-name表示想找的屬性詳下面說明
3 是否要找連結檔的屬性

屬性設定:
預設view-name使用basic 如basic: creationTime

basic:對應類別

BasicFileAttributeView

NameType
"lastModifiedTime"FileTime
"lastAccessTime"FileTime
"creationTime"FileTime
"size"Long
"isRegularFile"Boolean
"isDirectory"Boolean
"isSymbolicLink"Boolean
"isOther"Boolean
"fileKey"Object

dos:DosFileAttributeView

NameType
readonlyBoolean
hiddenBoolean
systemBoolean
archiveBoolean
posix:
PosixFileAttributeView
NameType
"permissions"Set<PosixFilePermission>
"group"GroupPrincipal

FileOwnerAttributeView

readAttributes

public static Map<String,Object> readAttributes(Path path,
String attributes,
 LinkOption... options)throws IOException
attributes:可以這樣設定
"*"Read all basic-file-attributes.
"size,lastModifiedTime,lastAccessTime"Reads the file size, last modified time, and last access time attributes.
"posix:*"Read all POSIX-file-attributes.
"posix:permissions,owner,size"Reads the POSX file permissions, owner, and file size.

public static <A extends BasicFileAttributes> A readAttributes(Path path,
                                               Class<A> type,
                                               LinkOption... options)
                                                    throws IOException
Usage Example: Suppose we want to read a file's attributes in bulk:
    Path path = ...
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
 

2013年5月8日 星期三

簡介跟java.util.concurrent某些相關類別!


  • Semaphore:

    建構時一定要有一個整數參數如下 new Semaphore(1)
    設定某數值當此數值為零時其他的執行序會進入wait,其他說明如下
    可設定某個數值如:Semaphore(2)
    
    
    在跑執行序時使用acquire()如能成功數值會扣1,當扣到為零時在呼叫acquire會產生wait的效果
    呼叫release()可將數值加回去!
    
    
     booleantryAcquire()            Acquires a permit from this semaphore, only if one is available at the time of invocation.
     booleantryAcquire(int permits)            Acquires the given number of permits from this semaphore, only if all are available at the time of invocation.
     booleantryAcquire(int permits, long timeout, TimeUnit unit)            Acquires the given number of permits from this semaphore, if all become available within the given waiting time and the current thread has not been interrupted.
     booleantryAcquire(long timeout, TimeUnit unit)            Acquires a permit from this semaphore, if one becomes available within the given waiting time and the current thread has not been interrupted.
    
    
    CountDownLatch :
    建構時可給一數值CountDownLatch(int count),不可小於0
  • 小於0會拋出
    Exception in thread "main" java.lang.IllegalArgumentException: count < 0
    當數值歸零時可喚醒被wait的執行序!
    使用countDown()減1
    await()設定等待的執行序
     voidawait()
              使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断
     booleanawait(long timeout, TimeUnit unit)
              使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。
     voidcountDown()
             Reduces the number of counts by one in this CountDownLatch object. If the 
    count reaches zero, all the (a)waiting threads are released. If the current count
    is already zero, nothing happens.
     longgetCount()
              返回当前计数。
     StringtoString()
              返回标识此锁存器及其状态的字符串。

    CyclicBarrier :

    執行序等待的數量到達設定時會執行某個Thread
    建構值必須有參數
    1. CyclicBarrier(int parties)
    这里的parties也是一个计数器,例如,初始化时parties里的计数是3,于是拥有该CyclicBarrier对象的线程当parties的计数为3时就唤醒,注:这里parties里的计数在运行时当调用CyclicBarrier:await()时,计数就加1,一直加到初始的值
    2. CyclicBarrier(int parties, Runnable barrierAction)
    當執行序到等待數量到設定時會呼叫barrierAction
    3 初始化不可為0或負數會產生IllegalArgumentException
  • 4 reset()重製到初始狀態。如果有任何線程在等待
  • 這Barrier,他們會拋出例外BrokenBarrierException。
  • 5 呼叫.await(1,TimeUnit.SECONDS);記得要tyr catch TimeoutException
  • 6 當.await(1,TimeUnit.SECONDS);過時之後會拋出TimeoutException與BrokenBarrierException

  • Exchanger :

    可在2個Thread中交換資料!

    class Talk1 extends Thread{
    Exchanger<String> _exhanger;
    public Talk1(Exchanger<String> exhanger){
    _exhanger = exhanger;
    this.start();
    }
    public void run(){
    try {
    String value = _exhanger.exchange("Hi..... Im JOJO");
    System.out.println("JoJo value:"+value);
    String value2 = _exhanger.exchange("Hi..... how are you? Howard");
    System.out.println("JoJo value:"+value2);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    class Talk2 extends Thread{
    Exchanger<String> _exhanger;
    public Talk2(Exchanger<String> exhanger){
    _exhanger = exhanger;
    this.start();
    }
    public void run(){
    try {
    TimeUnit.SECONDS.sleep(2);
    String value =  _exhanger.exchange("Hi..... Im Howard");
    System.out.println("HOWARD value:"+value);
    TimeUnit.SECONDS.sleep(2);
    String value2 =  _exhanger.exchange("Is good...");
    System.out.println("HOWARD value:"+value2);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }


    HOWARD value:Hi..... Im JOJO
    JoJo value:Hi..... Im Howard
    JoJo value:Is good...
    HOWARD value:Hi..... how are you? Howard

    Phaser :

    會設定一個數值,等到完成數量等於設定時會解開等待!
    phaser.arriveAndAwaitAdvance();//會增加完成數量並等待
    arriveAndDeregister//會移除註冊減少設定值 
    awaitAdvance會將執行緒wait直到指定的phaser到達目標
    可複寫 onAdvance(int phase, int numParties)達到時最後執行的方法,retun true 
    isTerminated就回傳true return false 就回傳False;
    phase--幾個階段 numParties--多少執行緒
    此方法回傳值會影響isTerminated
    phase(階段)由0開始
    awaitAdvance(int phase) 在指定的階段等待
    getArrivedParties() 取得已達到party的數量
    getUnarrivedParties() 取得未已達到party的數量




Thread狀態


Thread thread1=new Thread(new ExtendThread(), "thread1 "); Thread thread2=new Thread(thread1, "thread2 "); thread1.start();
thread2.start();

thread1.start();       // START

這會拋出錯誤訊息IllegalMonitorStateException 

因為Thread已進入
所以到了RUNNABLE狀態,start只有New狀態下才可呼叫


Thread有以下幾種狀態
NEW
RUNNABLE
BLOCKED
WAITING
TIMED_WAITING
TERMINATED


Livelocks and Lock Starvation

Deadlock
describes a situation where two or more threads are blocked forever, waiting for each other.

Livelocks

當兩個執行序在運作~1個作改變另一個作還原!~看似程式沒變化但實際上一直在改變
unable to make further progress.
unable to perform any real work.

Lock Starvation
當有很多個Thread是高優先權時,低優先權的Thread會一直拿不到Key 
 most of the time


Livelocks
ccurs when threads become so busy in responding to each other that they are unable to perform any real work.

Deadlock
Thread 1 and 2 are said to be deadlocked when Thread 1 is blocked waiting for Thread 2 to release a resource, while Thread 2 is blocked waiting for Thread 1 to release another resource.

Starvation
when a thread is frequently unable to get access to a resource because the resource is hogged by other threads most of the time.
官方說法:
unable to gain regular access to shared resources and is unable to make progress. 
This happens when shared resources are made unavailable for long periods by "greedy" threads.

2013年5月7日 星期二

BlockingQueue

1 BlockingQueue不接受null元素
BlockingQueue does not accept null elements. Implementations throw NullPointerException
2 下表一些常用方法
Throws exceptionSpecial valueBlocksTimes out
Insertadd(e)offer(e)put(e)offer(e, time, unit)
Removeremove()poll()take()poll(time, unit)
Examineelement()peek()not applicablenot applicable

3 如果限定了BlockingQueue長度時最好使用上標Special value的那一些方法

BlockingQueue本身的方法是线程安全的
但是addAll, containsAll, retainAll and removeAll不是线程安全的。



FileVisitor注意事項


1 FileVisitor 搜尋目錄時不一定會使用什麼順序
2 如果你想刪除某個目錄請在postVisitDirectory方法實作
因為要刪除目錄前目錄的檔案要先移除
3 By default, walkFileTree does not follow symbolic links.


如想跟蹤連結使用

  1.  EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);   
  2.         try {  
  3.             Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk);   
  4.         } catch (IOException e) {  
  5.             System.err.println(e);  
  6.         }  
Integer.MAX_VALUE參數指的是搜尋深度,如果是0不會搜尋指定目錄下的任何檔案與目錄
如果是1會收指定目錄下的那一層如下

dir 為目錄
file_x 為檔案

              MyDir

  dir_1      dir_2   dir_3 file_1

file_1_2

如設零指會找MyDir下的檔案會搜尋到指會搜尋到有MyDir
指定為1 會找到 dir_1 , dir_2,dir_3,file_1




  • preVisitDirectory – Invoked before a directory's entries are visited.//顯示檔案之前會先讀取此方法讀取目錄
  • postVisitDirectory – Invoked after all the entries in a directory are visited. If any errors are encountered, the specific exception is passed to the method.
  • 檔案都讀取好了最後才會讀取此方法
  • visitFile – Invoked on the file being visited. The file's BasicFileAttributes is passed to the method, or you can use the file attributes package to read a specific set of attributes. For example, you can choose to read the file's DosFileAttributeViewto determine if the file has the "hidden" bit set.
  • 顯示檔案的部份
  • visitFileFailed – Invoked when the file cannot be accessed. The specific exception is passed to the method. You can choose whether to throw the exception, print it to the console or a log file, and so on.
  • 如有錯誤會在這處理
preVisitDirectory(T dir, BasicFileAttributes attrs)
visitFile(T file, BasicFileAttributes attrs)
visitFileFailed(T file, IOException exc)
postVisitDirectory(T dir, IOException exc)-->參數是IOExecption

visitFileFailed  postVisitDirectory 內的都會傳入一個IOExecption
什麼狀況下會傳入ㄌㄟ~當讀取的資料夾或檔案有問題時,如權限問題等等~~
如我將某一個目錄改成700 讀取權限,跑walkFileTree就會進入visitFileFailed
當目錄進入visitFileFailed就不會讀取postVisitDirectory

讀取順序

FileVisitResult參數


FileVisitResult.CONTINUE--就一直往下找


FileVisitResult.SKIP_SUBTREE-->放在preVisitDirectory中才有實用價值
跟迴圈當中的continue效果相同,當放在preVisitDirectory時不會執行postVisitDirectory

 FileVisitResult.SKIP_SIBLINGS-->當放在preVisitDirectory時不會執行postVisitDirectory

FileVisitResult.TERMINATE-->直接離開迴圈
以上參數會用在
extends SimpleFileVisitor



2013年5月6日 星期一

OpenOptions Parameter

READ and TRUNCATE_EXISTING (or WRITE, APPEND, or DELETE_ON_CLOSE) cannot go together.
 READ and SYNC (or DSYNC) cannot go together either because when a file is opened for READ, there is nothing to synch.


CREATE and READ do not make sense if put together and therefore


new OpenOption[]{StandardOpenOption.READ, StandardOpenOption.APPEND}

new OpenOption[]{StandardOpenOption.APPEND, StandardOpenOption.TRUNCATE_EXISTING}

new OpenOption[]{StandardOpenOption.READ, StandardOpenOption.SYNC}

以上都是無效的配對組合
  • WRITE – Opens the file for write access.
  • APPEND – Appends the new data to the end of the file. This option is used with the WRITE or CREATE options.不可與READ or TRUNCATE_EXISTING options一起使用!

  • TRUNCATE_EXISTING – Truncates the file to zero bytes. This option is used with the WRITE option.//先將檔案清空在寫入
  • CREATE_NEW – Creates a new file and throws an exception if the file already exists.//如建立的檔案已存在會產生Exception
  • CREATE – Opens the file if it exists or creates a new file if it does not.//
  • 使用在write時會將第一筆資料欄位作取代的動作
  • 有相同檔案時不會拋出Exception
  • DELETE_ON_CLOSE – Deletes the file when the stream is closed. This option is useful for temporary files.//當關閉連線時將檔案刪除
  • SPARSE – Hints that a newly created file will be sparse. This advanced option is honored on some file systems, such as NTFS, where large files with data "gaps" can be stored in a more efficient manner where those empty gaps do not consume disk space.
  • SYNC – Keeps the file (both content and metadata) synchronized with the underlying storage device.
  • DSYNC – Keeps the file content synchronized with the underlying storage device.
SYNC requires that all data--SYNC 會同時將meta data跟資料一起寫到硬碟
SYNC makes sure that both - the data and meta data are synchronized with the storage device. Thus, it makes files operations even slower than DSYNC option.

DSYNC -->只會將當案寫到硬碟
DSYNC keeps only the file content and not the file meta data synchronized with the underlying storage device.
用法如下:
Path path = ...
     byte[] bytes = ...
     Files.write(path, bytes, StandardOpenOption.APPEND);

預設使用 StandardOpenOption.CREATE;
StandardOpenOption.TRUNCATE_EXISTING;

NOFOLLOW_LINKS

LinkOption.NOFOLLOW_LINKS
不會偵測LINKS來源是否存在,只關注目前links檔案資訊!



Path source = Paths.get("/Users/user/tmp/test_2_dir/value3_in");



我將value3_in的來源移除後:
System.out.println("Copy OK....:"+Files.exists(source,LinkOption.NOFOLLOW_LINKS));
1 印出true
System.out.println("Copy OK....:"+Files.exists(source));

2 印出false





2013年5月5日 星期日

JAVA_NIO2_2_FILES

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不會刪除實體只刪除連接


File. createDirectory or  createDirectories


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-->可以建立子目錄

當存在的檔案不是資料夾時會拋出錯誤
FileAlreadyExistsException - if dir exists but is not a directory (optional specific exception)


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