Commit | Line | Data |
---|---|---|
f4a474e3 MAL |
1 | /******************************************************************************* |
2 | * Copyright (c) 2014 Ericsson | |
3 | * | |
4 | * All rights reserved. This program and the accompanying materials are made | |
5 | * available under the terms of the Eclipse Public License v1.0 which | |
6 | * accompanies this distribution, and is available at | |
7 | * http://www.eclipse.org/legal/epl-v10.html | |
8 | * | |
9 | * Contributors: | |
10 | * Marc-Andre Laperle - Initial API and implementation | |
11 | *******************************************************************************/ | |
12 | ||
13 | package org.eclipse.linuxtools.internal.ctf.core; | |
14 | ||
15 | import java.io.IOException; | |
16 | import java.nio.ByteBuffer; | |
17 | import java.nio.channels.FileChannel; | |
18 | ||
f4a474e3 MAL |
19 | /** |
20 | * A common utility for mapping a ByteBuffer safely to work around a bug on | |
21 | * Windows which prevents deleting a file after it was mapped. On Windows, the | |
22 | * ByteBuffer will be allocated and the file will be read instead of being | |
23 | * mapped. | |
24 | * | |
25 | * http://bugs.java.com/view_bug.do?bug_id=4715154 | |
26 | */ | |
27 | public class SafeMappedByteBuffer { | |
28 | ||
882c5741 | 29 | private static final boolean IS_WIN32 = System.getProperty("os.name").startsWith("Windows"); //$NON-NLS-1$//$NON-NLS-2$ |
f4a474e3 MAL |
30 | |
31 | /** | |
32 | * Maps a region of this channel's file directly into memory. On Windows, | |
33 | * this will allocate a new ByteBuffer and read the file. | |
34 | * | |
35 | * @param fc | |
36 | * the file channel | |
37 | * @param mode | |
38 | * the mapping mode | |
39 | * @param position | |
40 | * the position within the file | |
41 | * @param size | |
42 | * the size of the region to be mapped (or read) | |
43 | * @return the mapped ByteBuffer | |
44 | * @throws IOException | |
45 | * on FileChannel operations failures | |
46 | */ | |
47 | public static ByteBuffer map(FileChannel fc, FileChannel.MapMode mode, long position, long size) throws IOException { | |
48 | ByteBuffer byteBuffer; | |
49 | if (IS_WIN32) { | |
50 | byteBuffer = ByteBuffer.allocate((int) size); | |
51 | fc.read(byteBuffer, position); | |
52 | } else { | |
53 | byteBuffer = fc.map(mode, position, size); | |
54 | } | |
55 | ||
56 | return byteBuffer; | |
57 | } | |
58 | } |