Создать копию файла java

Copying a File or Directory

You can copy a file or directory by using the copy(Path, Path, CopyOption. ) method. The copy fails if the target file exists, unless the REPLACE_EXISTING option is specified.

Directories can be copied. However, files inside the directory are not copied, so the new directory is empty even when the original directory contains files.

When copying a symbolic link, the target of the link is copied. If you want to copy the link itself, and not the contents of the link, specify either the NOFOLLOW_LINKS or REPLACE_EXISTING option.

This method takes a varargs argument. The following StandardCopyOption and LinkOption enums are supported:

  • REPLACE_EXISTING – Performs the copy even when the target file already exists. If the target is a symbolic link, the link itself is copied (and not the target of the link). If the target is a non-empty directory, the copy fails with the DirectoryNotEmptyException exception.
  • COPY_ATTRIBUTES – Copies the file attributes associated with the file to the target file. The exact file attributes supported are file system and platform dependent, but last-modified-time is supported across platforms and is copied to the target file.
  • NOFOLLOW_LINKS – Indicates that symbolic links should not be followed. If the file to be copied is a symbolic link, the link is copied (and not the target of the link).

If you are not familiar with enums , see Enum Types.

The following shows how to use the copy method:

import static java.nio.file.StandardCopyOption.*; . Files.copy(source, target, REPLACE_EXISTING);

In addition to file copy, the Files class also defines methods that may be used to copy between a file and a stream. The copy(InputStream, Path, CopyOptions. ) method may be used to copy all bytes from an input stream to a file. The copy(Path, OutputStream) method may be used to copy all bytes from a file to an output stream.

The Copy example uses the copy and Files.walkFileTree methods to support a recursive copy. See Walking the File Tree for more information.

Источник

Как копировать файлы в 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.

Читайте также:  Node js html head

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 а редиска.

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

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

Читайте также:  Debian run python script

Источник

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

Читайте также:  Python django admin view

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

Источник

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