Guest User

Shared File Lock

a guest
Jun 17th, 2016
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.RandomAccessFile;
  5. import java.nio.channels.FileChannel;
  6. import java.nio.channels.FileLock;
  7. import java.nio.charset.StandardCharsets;
  8. import java.nio.file.Files;
  9. import java.util.Arrays;
  10.  
  11. public class SomeClass {
  12.   public static void main(final String[] args) throws Exception {
  13.     final File file = File.createTempFile("SharedLockDemo", ".tmp");
  14.     try (FileOutputStream fs = new FileOutputStream(file)) {
  15.       fs.write("HELLO".getBytes(StandardCharsets.US_ASCII));
  16.     }
  17.  
  18.     if (!file.exists())
  19.       throw new FileNotFoundException();
  20.     try (final RandomAccessFile raf = new RandomAccessFile(file, "r");
  21.         FileChannel channel = raf.getChannel()) {
  22.       // Must be shared, since we are only in read access mode.
  23.       final FileLock lock = channel.lock(0, Long.MAX_VALUE, true);
  24.       final long size = channel.size();
  25.       System.out.println("Size: " + size); // should be |HELLO| = 5
  26.  
  27.       final String[] commands = new String[3];
  28.       commands[0] = "CMD"; // CMD startet echten neuen Prozess
  29.       commands[1] = "/C"; // Führt folgende Befehle aus:
  30.       commands[2] = "ECHO BOGUS > \"" + file.getCanonicalPath()
  31.           + "\" || EXIT 1"; // String Ausgabe
  32.  
  33.       System.out.println("Commands: " + Arrays.toString(commands));
  34.       // Befehl ausführen:
  35.       final Process process = Runtime.getRuntime().exec(commands);
  36.       final int exitValue = process.waitFor();
  37.       // I'd expect the value to be 1.
  38.       System.out.println("Exit Value: " + exitValue);
  39.  
  40.       lock.release();
  41.  
  42.       System.out.println("Contents of file:");
  43.       final byte[] contents = Files.readAllBytes(file.toPath());
  44.       if (contents.length == 0)
  45.         System.out.println("<EMPTY>");
  46.       else
  47.         System.out.println(new String(contents, StandardCharsets.US_ASCII));
  48.     }
  49.  
  50.   }
  51.  
  52. /* OUTPUT (Windows 7, Java 8):
  53.  
  54. Size: 5
  55. Commands: [CMD, /C, ECHO BOGUS > "C:\Users\Claude\AppData\Local\Temp\SharedLockDemo4948636556524834177.tmp" || EXIT 1]
  56. Exit Value: 0
  57. Contents of file:
  58. <EMPTY>
  59.  
  60. */
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment