Best Testcontainers-java code snippet using org.testcontainers.utility.MountableFile.deleteOnExit
Source:MountableFile.java  
...203        } catch (IOException e) {204            throw new IllegalStateException("Failed to process JAR file when extracting classpath resource: " + hostPath, e);205        }206        // Mark temporary files/dirs for deletion at JVM shutdown207        deleteOnExit(tmpLocation.toPath());208        try {209            return tmpLocation.getCanonicalPath();210        } catch (IOException e) {211            throw new IllegalStateException(e);212        }213    }214    private File createTempDirectory() {215        try {216            if (SystemUtils.IS_OS_MAC) {217                return Files.createTempDirectory(Paths.get(OS_MAC_TMP_DIR), TESTCONTAINERS_TMP_DIR_PREFIX).toFile();218            }219            return Files.createTempDirectory(TESTCONTAINERS_TMP_DIR_PREFIX).toFile();220        } catch  (IOException e) {221            return new File(TESTCONTAINERS_TMP_DIR_PREFIX + Base58.randomString(5));222        }223    }224    @SuppressWarnings("ResultOfMethodCallIgnored")225    private void copyFromJarToLocation(final JarFile jarFile,226                                       final JarEntry entry,227                                       final String fromRoot,228                                       final File toRoot) throws IOException {229        String destinationName = entry.getName().replaceFirst(fromRoot, "");230        File newFile = new File(toRoot, destinationName);231        log.debug("Copying resource {} from JAR file {}",232                fromRoot,233                jarFile.getName());234        if (!entry.isDirectory()) {235            // Create parent directories236            Path parent = newFile.getAbsoluteFile().toPath().getParent();237            parent.toFile().mkdirs();238            newFile.deleteOnExit();239            try (InputStream is = jarFile.getInputStream(entry)) {240                Files.copy(is, newFile.toPath());241            } catch (IOException e) {242                log.error("Failed to extract classpath resource " + entry.getName() + " from JAR file " + jarFile.getName(), e);243                throw e;244            }245        }246    }247    private void deleteOnExit(final Path path) {248        Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> recursiveDeleteDir(path)));249    }250    /**251     * {@inheritDoc}252     */253    @Override254    public void transferTo(final TarArchiveOutputStream outputStream, String destinationPathInTar) {255        recursiveTar(destinationPathInTar, this.getResolvedPath(), this.getResolvedPath(), outputStream);256    }257    /*258     * Recursively copies a file/directory into a TarArchiveOutputStream259     */260    private void recursiveTar(String entryFilename, String rootPath, String itemPath, TarArchiveOutputStream tarArchive) {261        try {...deleteOnExit
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.containers.wait.strategy.Wait;3import org.testcontainers.utility.MountableFile;4import java.io.File;5import java.nio.file.Files;6import java.nio.file.Path;7import java.nio.file.Paths;8import java.nio.file.StandardCopyOption;9public class TestContainer {10    public static void main(String[] args) throws Exception {11        Path tempFile = Files.createTempFile("test", ".txt");12        Path tempFileCopy = Paths.get(tempFile.getParent().toString(), "tempFileCopy.txt");13        Files.copy(tempFile, tempFileCopy, StandardCopyOption.REPLACE_EXISTING);14        MountableFile mountableFile = MountableFile.forHostPath(tempFileCopy.toString());15        GenericContainer container = new GenericContainer("busybox:latest")16                .withCommand("tail", "-f", "/dev/null")17                .withCopyFileToContainer(mountableFile, "/tempFileCopy.txt")18                .waitingFor(Wait.forLogMessage(".*", 1));19        container.start();20        Files.delete(tempFile);21        Files.delete(tempFileCopy);22    }23}24Files.delete(tempFileCopy);25	at java.base/java.io.WinNTFileSystem.delete0(Native Method)26	at java.base/java.io.WinNTFileSystem.delete(WinNTFileSystem.java:281)27	at java.base/java.io.File.delete(File.java:1077)28	at org.testcontainers.utility.MountableFile.deleteOnExit(MountableFile.java:363)29	at org.testcontainers.containers.GenericContainer.copyFileToContainer(GenericContainer.java:1264)30	at org.testcontainers.containers.GenericContainer.copyFileToContainer(GenericContainer.java:1258)31	at org.testcontainers.containers.GenericContainer.copyFileToContainer(GenericContainer.java:1253)32	at org.testcontainers.containers.GenericContainer.copyFileToContainer(GenericContainer.java:1248)33	at org.testcontainers.containers.GenericContainer.withCopyFileToContainer(GenericContainer.javadeleteOnExit
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer2import org.testcontainers.containers.output.Slf4jLogConsumer3import org.testcontainers.utility.MountableFile4import org.testcontainers.containers.wait.strategy.Wait5import org.slf4j.LoggerFactory6import java.io.File7final logger = LoggerFactory.getLogger("testcontainers")8final container = new GenericContainer("ubuntu:latest")9container.withCommand("tail", "-f", "/dev/null")10container.withFileSystemBind("src/test/resources", "/tmp", BindMode.READ_WRITE)11container.withFileSystemBind("src/test/resources", "/tmp2", BindMode.READ_WRITE)12container.withFileSystemBind("src/test/resources", "/tmp3", BindMode.READ_WRITE)13container.withFileSystemBind("src/test/resources", "/tmp4", BindMode.READ_WRITE)14container.withFileSystemBind("src/test/resources", "/tmp5", BindMode.READ_WRITE)15container.withFileSystemBind("src/test/resources", "/tmp6", BindMode.READ_WRITE)16container.withFileSystemBind("src/test/resources", "/tmp7", BindMode.READ_WRITE)17container.withFileSystemBind("src/test/resources", "/tmp8", BindMode.READ_WRITE)18container.withFileSystemBind("src/test/resources", "/tmp9", BindMode.READ_WRITE)19container.withFileSystemBind("src/test/resources", "/tmp10", BindMode.READ_WRITE)20container.withFileSystemBind("src/test/resources", "/tmp11", BindMode.READ_WRITE)21container.withFileSystemBind("src/test/resources", "/tmp12", BindMode.READ_WRITE)22container.withFileSystemBind("src/test/resources", "/tmp13", BindMode.READ_WRITE)23container.withFileSystemBind("src/test/resources", "/tmp14", BindMode.READ_WRITE)24container.withFileSystemBind("src/test/resources", "/tmp15", BindMode.READ_WRITE)25container.withFileSystemBind("src/test/resources", "/tmp16", BindMode.READ_WRITE)26container.withFileSystemBind("src/test/resources", "/tmp17", BindMode.READ_WRITE)27container.withFileSystemBind("src/test/resources", "/tmp18", BindMode.READ_WRITE)28container.withFileSystemBind("src/test/resources", "/tmp19", BindMode.READ_WRITE)29container.withFileSystemBind("src/test/resources", "/tmp20", BindMode.READ_WRITE)30container.withFileSystemBind("src/test/resources", "/tmp21", BindMode.READ_WRITE)31container.withFileSystemBind("src/test/resources", "/tmp22", BindMode.READ_WRITE)32container.withFileSystemBind("src/test/resources", "/tmp23", BindMode.READdeleteOnExit
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.utility.MountableFile;3public class MountableFileDemo {4    public static void main(String[] args) {5        GenericContainer container = new GenericContainer("alpine:3.8");6        container.withCommand("tail", "-f", "/dev/null");7        container.start();8        MountableFile mountableFile = MountableFile.forClasspathResource("test.txt");9        container.copyFileToContainer(mountableFile, "/tmp/test.txt");10        System.out.println(container.execInContainer("cat", "/tmp/test.txt").getStdout());11        System.out.println(mountableFile.getFile().exists());12        mountableFile.deleteOnExit();13        System.out.println(mountableFile.getFile().exists());14        container.stop();15    }16}deleteOnExit
Using AI Code Generation
1import org.junit.Test;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.utility.MountableFile;4public class TestContainer {5    public void test() {6        try (GenericContainer container = new GenericContainer("alpine")) {7            container.withCommand("tail", "-f", "/dev/null");8            container.start();9            MountableFile mountableFile = MountableFile.forClasspathResource("test.txt");10            mountableFile.deleteOnExit();11            container.copyFileToContainer(mountableFile, "/test.txt");12        }13    }14}15[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ testcontainers ---16[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ testcontainers ---17[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ testcontainers ---18[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ testcontainers ---19[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ testcontainers ---deleteOnExit
Using AI Code Generation
1import org.testcontainers.containers.GenericContainer;2import org.testcontainers.utility.MountableFile;3import java.io.File;4import java.io.IOException;5public class TestContainerFileMounting {6    public static void main(String[] args) throws IOException, InterruptedException {7        File file = new File("src/main/resources/test.txt");8        file.createNewFile();9        try (GenericContainer container = new GenericContainer("alpine:3.12")10                .withCommand("tail", "-f", "/dev/null")11                .withFileSystemBind("src/main/resources/test.txt", "/test.txt")12                .withFileSystemBind(file, "/test2.txt", MountableFile.DELETE_ON_CLOSE)13                .withFileSystemBind(file, "/test3.txt", MountableFile.DELETE_ON_EXIT)14                .withFileSystemBind(file, "/test4.txt", MountableFile.DELETE_ON_SHUTDOWN)15                .withFileSystemBind(file, "/test5.txt", MountableFile.DELETE_ON_STOP)16                .withFileSystemBind(file, "/test6.txt", MountableFile.DELETE_ON_UNMOUNT)17        ) {18            container.start();19            Thread.sleep(10000);20            System.out.println("Container started");21        }22    }23}deleteOnExit
Using AI Code Generation
1public class MountableFileTest {2    public static void main(String[] args) {3        String filePath = "C:\\Users\\sudhanshu\\Desktop\\test.txt";4        MountableFile mountableFile = MountableFile.forHostPath(filePath);5        mountableFile.deleteOnExit();6        System.out.println("File deleted successfully!");7    }8}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
