Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.RandomAccessFile;
- import java.nio.channels.FileChannel;
- import java.nio.channels.FileLock;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.Files;
- import java.util.Arrays;
- public class SomeClass {
- public static void main(final String[] args) throws Exception {
- final File file = File.createTempFile("SharedLockDemo", ".tmp");
- file.deleteOnExit();
- try (FileOutputStream fs = new FileOutputStream(file)) {
- fs.write("HELLO".getBytes(StandardCharsets.US_ASCII));
- }
- if (!file.exists())
- throw new FileNotFoundException();
- try (final RandomAccessFile raf = new RandomAccessFile(file, "r");
- FileChannel channel = raf.getChannel()) {
- // Must be shared, since we are only in read access mode.
- final FileLock lock = channel.lock(0, Long.MAX_VALUE, true);
- final long size = channel.size();
- System.out.println("Size: " + size); // should be |HELLO| = 5
- final String[] commands = new String[3];
- commands[0] = "CMD"; // CMD startet echten neuen Prozess
- commands[1] = "/C"; // Führt folgende Befehle aus:
- commands[2] = "ECHO BOGUS > \"" + file.getCanonicalPath()
- + "\" || EXIT 1"; // String Ausgabe
- System.out.println("Commands: " + Arrays.toString(commands));
- // Befehl ausführen:
- final Process process = Runtime.getRuntime().exec(commands);
- final int exitValue = process.waitFor();
- // I'd expect the value to be 1.
- System.out.println("Exit Value: " + exitValue);
- lock.release();
- System.out.println("Contents of file:");
- final byte[] contents = Files.readAllBytes(file.toPath());
- if (contents.length == 0)
- System.out.println("<EMPTY>");
- else
- System.out.println(new String(contents, StandardCharsets.US_ASCII));
- }
- }
- /* OUTPUT (Windows 7, Java 8):
- Size: 5
- Commands: [CMD, /C, ECHO BOGUS > "C:\Users\Claude\AppData\Local\Temp\SharedLockDemo4948636556524834177.tmp" || EXIT 1]
- Exit Value: 0
- Contents of file:
- <EMPTY>
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement