Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.nio.ByteBuffer;
- import java.nio.channels.FileChannel;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.function.Consumer;
- public class LockedFile {
- private String filename;
- public LockedFile(String filename){
- this.filename = filename;
- }
- public List<String> read(){
- List<String> lines = new ArrayList<>();
- lockFile(filename, fileChannel -> {
- try(Scanner scanner = new Scanner(fileChannel)){
- while (scanner.hasNextLine()){
- lines.add(scanner.nextLine());
- }
- }
- });
- return lines;
- }
- public void write(List<String> lines){
- lockFile(filename, fileChannel -> {
- // point to EOF
- try {
- fileChannel.position(fileChannel.size());
- } catch (IOException e) {
- e.printStackTrace();
- }
- for(String line : lines){
- try {
- fileChannel.write(ByteBuffer.wrap((line + "\r\n").getBytes()));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- });
- }
- private synchronized void lockFile(String filename, Consumer<FileChannel> fileChannelConsumer){
- File file = new File(filename);
- try (FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel()){
- // blocking call - throws when lock can't be acquired
- fileChannel.lock();
- fileChannelConsumer.accept(fileChannel);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement