Advertisement
Guest User

Untitled

a guest
Jun 13th, 2020
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. import java.io.*;
  2. import java.nio.ByteBuffer;
  3. import java.nio.channels.FileChannel;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.Scanner;
  7. import java.util.function.Consumer;
  8.  
  9. public class LockedFile {
  10.  
  11.     private String filename;
  12.  
  13.     public LockedFile(String filename){
  14.         this.filename = filename;
  15.     }
  16.  
  17.     public List<String> read(){
  18.         List<String> lines = new ArrayList<>();
  19.  
  20.         lockFile(filename, fileChannel -> {
  21.             try(Scanner scanner = new Scanner(fileChannel)){
  22.                 while (scanner.hasNextLine()){
  23.                     lines.add(scanner.nextLine());
  24.                 }
  25.             }
  26.         });
  27.  
  28.         return lines;
  29.     }
  30.  
  31.     public void write(List<String> lines){
  32.         lockFile(filename, fileChannel -> {
  33.             // point to EOF
  34.             try {
  35.                 fileChannel.position(fileChannel.size());
  36.             } catch (IOException e) {
  37.                 e.printStackTrace();
  38.             }
  39.  
  40.             for(String line : lines){
  41.                 try {
  42.                     fileChannel.write(ByteBuffer.wrap((line + "\r\n").getBytes()));
  43.                 } catch (IOException e) {
  44.                     e.printStackTrace();
  45.                 }
  46.             }
  47.         });
  48.     }
  49.  
  50.     private synchronized void lockFile(String filename, Consumer<FileChannel> fileChannelConsumer){
  51.         File file = new File(filename);
  52.         try (FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel()){
  53.  
  54.             // blocking call - throws when lock can't be acquired
  55.             fileChannel.lock();
  56.  
  57.             fileChannelConsumer.accept(fileChannel);
  58.  
  59.         } catch (IOException e) {
  60.             e.printStackTrace();
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement