Windows: перемещение файла, который был ранее отображен в памяти, завершается неудачно

-: = ИЗМЕНЕНО ДЛЯ УПРОЩЕНИЯ =: -



Я сталкиваюсь с проблемой в процессе переноса кода из среды Linux (Ubuntu LTS 12.4) в Windows Server 2008.

Мне нужно использовать файл с отображенной памятью, но я не могу предотвратить ошибку ниже в Windows.

Эта проблема воспроизводится в модульном тесте ниже. 2 теста успешно выполняются в Linux, но в Windows - тестtestWithRandowmAccessFile не удается с трассировкой стека внизу.



В чем коренная причинаtestWithRandowmAccessFile тест не пройден?

Как я должен реализовать это на Windows?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

public class TestIOOnWindows {   

    @Test
    public void testWithRandowmAccessFile() throws IOException {
        final File sourceFile = new File("source.txt");
        final File manipulatedFile = new File("manipulated.txt");
        final File targetFile = new File("target.txt");

        try
        (
            FileInputStream sourceInputStream = new FileInputStream(sourceFile);
            RandomAccessFile manipulated = new RandomAccessFile(manipulatedFile, "rw");
            FileChannel fcOut = manipulated.getChannel()
        ) 
        {
            byte[] sourceBytes = new byte[Long.valueOf(sourceFile.length()).intValue()];
            IOUtils.read(sourceInputStream, sourceBytes);

            final int length = sourceBytes.length;            

            // ========= with this single line on Windows, the move fails ======
            MappedByteBuffer byteBuffer = fcOut.map(FileChannel.MapMode.READ_WRITE, 0, length);
            // commenting this line would not prevent the error on Windows
            byteBuffer.put(sourceBytes, 0, length);            
        }

        Files.move(
                Paths.get(manipulatedFile.getAbsolutePath()),
                Paths.get(targetFile.getAbsolutePath()),
                StandardCopyOption.REPLACE_EXISTING);
    }

    @Test
    public void testWithFileOutputStream() throws IOException {
        final File sourceFile = new File("source.txt");
        final File manipulatedFile = new File("manipulated.txt");
        final File targetFile = new File("target.txt");

        try
        (
            FileInputStream sourceInputStream = new FileInputStream(sourceFile);
            FileOutputStream manipulatedOutputStream = new FileOutputStream(manipulatedFile);
            FileChannel fcIn = sourceInputStream.getChannel();
            FileChannel fcOut = manipulatedOutputStream.getChannel()
        ) 
        {
            final long length = sourceFile.length();

            // ========= with this single line on Windows, the move succeed ====
            fcIn.transferTo(0, length, fcOut);
        }

        Files.move(
                Paths.get(manipulatedFile.getAbsolutePath()),
                Paths.get(targetFile.getAbsolutePath()),
                StandardCopyOption.REPLACE_EXISTING);
    }
}



добавление трассировки, которую я получаю при запуске модульного теста из командной строки в Windows.

There was 1 failure:
1) testWithRandowmAccessFile(TestIOOnWindows) java.nio.file.FileSystemException: C:\Users\Administrator\AppData\Local\Temp\manipulated.txt -> C:\Users\Administrator\AppData\Local\Temp\target.txt: The process cannot access the file because it is being used by another process.

    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileCopy.move(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.move(Unknown Source)
    at java.nio.file.Files.move(Unknown Source)
    ===> at TestIOOnWindows.testWithRandowmAccessFile(TestIOOnWindows.java:40) 

Ответы на вопрос(2)

Ваш ответ на вопрос