Advertisement
DulcetAirman

SharedLockDemo

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