本文實(shí)例講解了5種解決Java獨(dú)占寫(xiě)文件的方法,包含自己的一些理解,如若有不妥的地方歡迎大家提出。
方案1:利用RandomAccessFile的文件操作選項(xiàng)s,s即表示同步鎖方式寫(xiě)
1
|
RandomAccessFile file = new RandomAccessFile(file, "rws" ); |
方案2:利用FileChannel的文件鎖
1
2
3
4
5
6
7
8
9
10
|
File file = new File( "test.txt" ); FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel(); FileLock fileLock = null ; while ( true ) { fileLock = channel.tryLock( 0 , Long.MAX_VALUE, false ); // true表示是共享鎖,false則是獨(dú)享鎖定 if (fileLock!= null ) break ; else // 有其他線(xiàn)程占據(jù)鎖 sleep( 1000 ); } |
方案3:先將要寫(xiě)的內(nèi)容寫(xiě)入一個(gè)臨時(shí)文件,然后再將臨時(shí)文件改名(Hack方案,利用了緩沖+原子操作的原理)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class MyFile { private String fileName; public MyFile(String fileName) { this .fileName = fileName; } public synchronized void writeData(String data) throws IOException { String tmpFileName = UUID.randomUUID().toString()+ ".tmp" ; File tmpFile = new File(tmpFileName); FileWriter fw = new FileWriter(tmpFile); fw.write(data); fw.flush(); fw.close(); // now rename temp file to desired name, this operation is atomic operation under most os if (!tmpFile.renameTo(fileName) { // we may want to retry if move fails throw new IOException( "Move failed" ); } } } |
方案4:根據(jù)文件路徑封裝文件,并且用synchronized控制寫(xiě)文件
1
2
3
4
5
6
7
8
9
10
11
12
|
public class MyFile { private String fileName; public MyFile(String fileName) { this .fileName = fileName; } public synchronized void writeData(String data) throws IOException { FileWriter fw = new FileWriter(fileName); fw.write(data); fw.flush(); fw.close(); } } |
方案5:我自己想出來(lái)的一個(gè)方案,不太精確。通過(guò)切換設(shè)置讀寫(xiě)權(quán)限控制,模擬設(shè)置一個(gè)可寫(xiě)標(biāo)記量(蛻變成操作系統(tǒng)中經(jīng)典的讀寫(xiě)問(wèn)題....)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class MyFile { private volatile boolean canWrite = true ; private String fileName; public MyFile(String fileName) { this .fileName = fileName; } public void writeData(String data) { while (!canWrite) { try { Thread.sleep( 100 ); } catch (InteruptedException ie) { } // 可以設(shè)置一個(gè)超時(shí)寫(xiě)時(shí)間 } canWrite = false ; // Now write file canWrite = true ; } } |
以上就是Java獨(dú)占寫(xiě)文件的解決方法,大家有沒(méi)有學(xué)會(huì),可以參考其他文章進(jìn)行學(xué)習(xí)理解。