檔案鎖
使用檔案鎖要用到
FileLock類
和
FileChannel類
,并且結合随機流
RandomAccessFile類
進行使用
RandomAccessFile建立的流在讀/寫檔案時可以使用檔案鎖,隻要不解除該鎖,那麼其他程式就無法對被鎖的檔案進行操作
使用檔案鎖
- 先試用
流建立指向檔案的流對象,模式必須是"rw"RandomAccessFile
- input調用方法
獲得一個連接配接到底層檔案的getChannel()
對象(信道)FileChannel
- 信道調用
或tryLock()
方法獲得一個lock()
(檔案鎖),這個過程就叫檔案加鎖FileLock
- 當檔案加鎖後将禁止任何應用程式對檔案進行操作或在進行加鎖,如果想讀寫檔案那麼必須要先解鎖
對檔案進行加鎖的例子
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class myWindow extends JFrame implements ActionListener {
JButton jButton;
JTextArea jTextArea;
File file;
FileChannel fileChannel;
FileLock fileLock;
RandomAccessFile randomAccessFile;
myWindow(){
setTitle("檔案鎖");
setBounds(300,300,500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
init();
validate();
}
void init(){
jTextArea = new JTextArea();
add(new JScrollPane(jTextArea), BorderLayout.CENTER);
jButton = new JButton("輸入一行");
jButton.addActionListener(this); //設定螢幕
add(jButton,BorderLayout.SOUTH);
try{
file = new File("C:\\Users\\Administrator\\Desktop","首頁文案.txt");
randomAccessFile = new RandomAccessFile(file,"rw");
fileChannel = randomAccessFile.getChannel(); //擷取檔案的通道
fileLock = fileChannel.tryLock(); //通道上鎖後放到鎖對象中
}
catch(Exception E){
}
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
try{
fileLock.release();
String s = randomAccessFile.readLine(); //将讀取的每一行放到字元串中
byte b [] = s.getBytes("ISO-8859-1"); //轉換編碼,否者會出現亂碼
String content = new String(b);
jTextArea.append("\n" + content); //讀取的一行放到文本框中
fileLock = fileChannel.tryLock();
if (s == null)
randomAccessFile.close();
}
catch(Exception e){
}
}
}
public class Example12_16 {
public static void main(String[] args) {
myWindow myWindow = new myWindow();
}
}
運作效果圖
解決亂碼的問題
RandomAccessFile流調用readLine()方法時讀取含有非ASCII字元的檔案時就會出現亂碼,因為有文字的存在,是以要解決這個問題就要将讀到的字元串重新編碼然後放到一個byte數組中
- 擷取每一行字元串後
- 用ISO-8859-1重新編碼
- 使用目前計算機的預設編碼将位元組數數組轉化為字元串
- 最後輸出的content就不會是亂碼了