Java copy file to file system

Copying a File in Java

Copying a file from one place to another in Java is a common task that we need to do in the applications. In this Java tutorial, we will see different ways to copy a file in Java.

Note that file copying is not an atomic operation – in the case of an I/O error, power loss, process termination, or other problems, the copying operation is not complete. If we need to guard against those conditions, we should employ other file-level synchronization.

In all given examples, we will be copying the content of testoriginal.txt to an another file testcopied.txt . The name and the location of the files can be replaced in any of the examples.

The Files class is in java.nio.file package. It provides the static methods that operate on files, directories, or other types of files.

  • By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same files, in which case the method completes without copying the file.
  • If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied).

Use one or more CopyOption enums to control how the copy should be done.

  • REPLACE_EXISTING : Any existing target file will be replaced.
  • COPY_ATTRIBUTES : Copy the file attributes from the source to the target file.
  • NOFOLLOW_LINKS : If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied.
Path source = Paths.get("c:/temp/testoriginal.txt"); Path target = Paths.get("c:/temp/testcopied.txt"); Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

2. Using FileChannel.transferTo()

If you are fond of FileChannel class for their brilliant performance, use this method. The key advantage here is that the JVM uses the OS’s access to DMA (Direct Memory Access) if present.

Using this technique, the data goes straight to/from disc to the bus, and then to the destination… bypassing any circuit through RAM or the CPU.

File fileToCopy = new File("c:/temp/testoriginal.txt"); FileInputStream inputStream = new FileInputStream(fileToCopy); FileChannel inChannel = inputStream.getChannel(); File newFile = new File("c:/temp/testcopied.txt"); FileOutputStream outputStream = new FileOutputStream(newFile); FileChannel outChannel = outputStream.getChannel(); inChannel.transferTo(0, fileToCopy.length(), outChannel); inputStream.close(); outputStream.close();

3. Using Commons IO’s FileUtils

To use Apache Commons IO, we will need to download the commons-io dependency and include in the project.

Use one of the following classes for copying one file to another.

  • FileUtils – Internally it uses the java.nio.file.Files class so it is equivalent to use the java.nio.file.Files.copy() function.
  • IOUtils – It copies bytes from a large (over 2GB) InputStream to an OutputStream . This method uses the provided buffer, so there is no need to use a BufferedInputStream .
File fileToCopy = new File("c:/temp/testoriginal.txt"); File newFile = new File("c:/temp/testcopied.txt"); FileUtils.copyFile(fileToCopy, newFile); // OR IOUtils.copy(new FileInputStream(fileToCopy), new FileOutputStream(newFile));

To use Guava, we will need to download the com.google.guava dependency and include in the project.

 com.google.guava guava 31.1-jre 

The Files class provides utility methods for working with files. The Files.copy() method copies all the bytes from one file to another.

File fileToCopy = new File("c:/temp/testoriginal.txt"); File newFile = new File("c:/temp/testcopied.txt"); Files.copy(fileToCopy, newFile);

After Java 7, there have not been any major improvements in the Java IO package. So for any later Java release (Java 8 to Java 14), we have to reply on above-listed techniques.

Читайте также:  Css input text field width

Источник

Как копировать файлы в Java

Обложка: Как копировать файлы в Java

В этой статье мы рассмотрим типичные способы копирования файлов в Java на примере четырех библиотек: встроенных IO и NIO.2 API и внешних Commons IO и Guava.

IO API (До JDK7)

При использовании этого встроенного пакета для копирования файла необходимо открыть файловый поток, пройтись циклом по его содержимому и записать его в результирующий поток.

@Test public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException < File copied = new File("src/test/resources/copiedWithIo.txt"); try ( InputStream in = new BufferedInputStream( new FileInputStream(original)); OutputStream out = new BufferedOutputStream( new FileOutputStream(copied))) < byte[] buffer = new byte[1024]; int lengthRead; while ((lengthRead = in.read(buffer)) >0) < out.write(buffer, 0, lengthRead); out.flush(); >> assertThat(copied).exists(); assertThat(Files.readAllLines(original.toPath()) .equals(Files.readAllLines(copied.toPath()))); > 

Довольно много кода для реализации базовой функции. К счастью, Java постепенно совершенствует свои встроенные библиотеки, и, начиная с JDK7, можно использовать более простой способ копирования с помощью NIO.2 API.

NIO.2 API (JDK7)

Эта библиотека улучшает производительность процедуры копирования за счет использования низкоуровневых точек входа.

По умолчанию новые скопированные файлы не могут переписать ранее созданные. Также нельзя скопировать атрибуты файла-источника. Но поведение метода Files.copy() может быть изменено при использовании специальных опций:

  • REPLACE_EXISTING — заменить файл, если он уже существовал,
  • COPY_ATTRIBUTES — скопировать метаданные в новый файл,
  • NOFOLLOW_LINKS — не переходить по символическим ссылкам.

Класс NIO.2 Files предоставляет несколько перегруженных методов copy() для копирования файлов и директорий в файловой системе.

@Test public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException < Path copied = Paths.get("src/test/resources/copiedWithNio.txt"); Path originalPath = original.toPath(); Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); assertThat(copied).exists(); assertThat(Files.readAllLines(originalPath) .equals(Files.readAllLines(copied))); >

Важно отметить, что копирование директорий — поверхностное, то есть файлы поддиректорий не скопируются.

Apache Commons IO

Для работы с библиотекой Commons IO нужно добавить зависимость:

Свежую версию библиотеки можно скачать с Maven Central.

Затем используем метод copyFile() , определенный в классе FileUtils . Он принимает на вход файл-источник и файл, в который будет скопирован исходный.

@Test public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException < File copied = new File( "src/test/resources/copiedWithApacheCommons.txt"); FileUtils.copyFile(original, copied); assertThat(copied).exists(); assertThat(Files.readAllLines(original.toPath()) .equals(Files.readAllLines(copied.toPath()))); >

Guava

И напоследок обратим внимание на библиотеку Guava. Для ее использования также необходимо добавить зависимость:

Последнюю версию библиотеки можно найти на Maven Central.

@Test public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException < File copied = new File("src/test/resources/copiedWithGuava.txt"); com.google.common.io.Files.copy(original, copied); assertThat(copied).exists(); assertThat(Files.readAllLines(original.toPath()) .equals(Files.readAllLines(copied.toPath()))); >

Что думаете?

Устроили «сайт знакомств» из найма.В место того чтобы понять что приходящие на собесодования Степашки по большей части интроверты и адаптироваться — лезут в душу со страными вопросами которые Степашек пугают.И упорно пилят гайды как понравится HRюшам.Детсад а не профессионализм.Причем программист в принципе вне круга коллег и общаться то уметь не обязан(а внутри пусть хоть как модемы пиликают).Общаться с кандидатом должен ументь именно HR. Иначе это не HR а редиска.

Читайте также:  Установка нескольких версий php ubuntu

Ребят, тут собрались ноунеймы которые не работают ни на одном языке, но пишут свое очень важное мнение в комментариях. Лучше проходите мимо и не читайте их. Ах да, учите go и устройтесь в яндекс)

Как вы собираетесь искать хороших сотрудников, если (в большинстве компаний) честных кандидатов отметают даже не пригласив на техническое собеседование?Если умение лгать является обязательным, чтобы устроиться к вам на работу, то не удивляйтесь что «сложно найти хорошего сотрудника».Я знаю о чем говорю. В нашей компании для продвижения программистов на аутсорс есть целая отдельная команда, которая полностью специализируется на «продаже сотрудников». Это люди, которые пристально изучают хотелки чсв hr-ов, пишут «идеальные» резюме и отвечают на все вопросы так, «как надо». А программист приходит только на техническое собеседование в конце.Хорошие сотрудники (как правило) не станут накручивать себе 20 лет стажа, рассказывать про мотивацию «не ради денег», отвечать на глупые вопросы про квадратные люки и прочую ерунду.Вам нужно не учить людей в интернете «как правильно отвечать на наши вопросы, чтобы вы у нас прошли собес», а мыслить шире и заниматься реальным поиском толковых специалистов, которые не обязаны иметь топовые софт-скилы.В противном случае — получайте «идеальные» резюме, написанные по единому шаблону и котов в мешке. И не забудьте пожаловаться что «сложно найти хорошего сотрудника».

Источник

Java Copy File — 4 Ways to Copy File in Java

Java Copy File - 4 Ways to Copy File in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java copy file is a very common operation. But java.io.File class doesn’t have any shortcut method to copy a file from source to destination. Here we will learn about four different ways we can copy file in java.

Java Copy File

java copy file, copy file in java, java file copy, java copy file to directory

  1. Java Copy File — Stream

This is the conventional way of file copy in java. Here we create two Files — source and destination. Then we create InputStream from source and write it to the destination file using OutputStream for java copy file operation. Here is the method that can be used for java copy file using streams.

private static void copyFileUsingStream(File source, File dest) throws IOException < InputStream is = null; OutputStream os = null; try < is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) >0) < os.write(buffer, 0, length); >> finally < is.close(); os.close(); >> 

Java NIO classes were introduced in Java 1.4 and FileChannel can be used to copy file in java. According to transferFrom() method javadoc, this way of copy file is supposed to be faster than using Streams for java copy files. Here is the method that can be used to copy a file using FileChannel.

private static void copyFileUsingChannel(File source, File dest) throws IOException < FileChannel sourceChannel = null; FileChannel destChannel = null; try < sourceChannel = new FileInputStream(source).getChannel(); destChannel = new FileOutputStream(dest).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); >finally < sourceChannel.close(); destChannel.close(); >> 

Apache Commons IO FileUtils.copyFile(File srcFile, File destFile) can be used to copy file in java. If you are already using Apache Commons IO in your project, it makes sense to use this for code simplicity. Internally it uses Java NIO FileChannel, so you can avoid this wrapper method if you are not already using it for other functions. Here is the method for using apache commons io for java copy file operation.

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException

If you are working on Java 7 or higher, you can use Files class copy() method to copy file in java. It uses File System providers to copy the files.

private static void copyFileUsingJava7Files(File source, File dest) throws IOException

Now to find out which is the fastest method, I wrote a test class and executed above methods one-by-one for copy file of 1 GB. In each call, I used different files to avoid any benefit to later methods because of caching.

package com.journaldev.files; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.FileChannel; import java.nio.file.Files; import org.apache.commons.io.FileUtils; public class JavaCopyFile < public static void main(String[] args) throws InterruptedException, IOException < File source = new File("/Users/pankaj/tmp/source.avi"); File dest = new File("/Users/pankaj/tmp/dest.avi"); //copy file conventional way using Stream long start = System.nanoTime(); copyFileUsingStream(source, dest); System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start)); //copy files using java.nio FileChannel source = new File("/Users/pankaj/tmp/sourceChannel.avi"); dest = new File("/Users/pankaj/tmp/destChannel.avi"); start = System.nanoTime(); copyFileUsingChannel(source, dest); System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start)); //copy files using apache commons io source = new File("/Users/pankaj/tmp/sourceApache.avi"); dest = new File("/Users/pankaj/tmp/destApache.avi"); start = System.nanoTime(); copyFileUsingApacheCommonsIO(source, dest); System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start)); //using Java 7 Files class source = new File("/Users/pankaj/tmp/sourceJava7.avi"); dest = new File("/Users/pankaj/tmp/destJava7.avi"); start = System.nanoTime(); copyFileUsingJava7Files(source, dest); System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start)); >> 

Here is the output of the above program, note that I commented above code to make sure every time only one method is used for java file copy operation.

Time taken by Stream Copy = 44582575000 Time taken by Channel Copy = 104138195000 Time taken by Apache Commons IO Copy = 108396714000 Time taken by Java7 Files Copy = 89061578000 

From the output, it’s clear that Stream Copy is the best way to copy File in Java. But it’s a very basic test. If you are working on a performance intensive project, then you should try out different methods for java copy file and note down the timings to figure out the best approach for your project. You should also play around different ways of java copy files based on your average size of the file. I have created a YouTube video for 4 ways to copy the file in java, you can watch it to learn more. https://www.youtube.com/watch?v=op6tgG95zek

Читайте также:  Процентное деление в питоне

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью