package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class CopyExample {
public static void main(String... args) throws IOException {
Path tempFile = Files.createTempFile("my-file", ".txt");
System.out.println("file to copy: " + tempFile);
Path copiedFile = Files.copy(
tempFile,
Paths.get("C:\\temp\\" + tempFile.getFileName()),
StandardCopyOption.REPLACE_EXISTING
);
System.out.println("file copied: " + copiedFile);
System.out.println("copied file exits: " + Files.exists(copiedFile));
}
}
Output
file to copy: C:\Users\Joe\AppData\Local\Temp\my-file12337966864934082418.txt
file copied: C:\temp\my-file12337966864934082418.txt
copied file exits: true
package com.logicbig.example.files;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class CopyExample2 {
public static void main(String... args) throws IOException {
InputStream inputStream = new ByteArrayInputStream("test string".getBytes());
System.out.println("inputStream bytes available: " + inputStream.available());
Path target = Paths.get("C:\\temp\\copy-file-test.txt");
long bytesCopied = Files.copy(
inputStream,
target,
StandardCopyOption.REPLACE_EXISTING
);
System.out.println("file copied: " + target);
System.out.println("copied file exits: " + Files.exists(target));
System.out.println("bytes copied: " + bytesCopied);
System.out.println("copied file size: " + Files.size(target));
}
}
Output
inputStream bytes available: 11
file copied: C:\temp\copy-file-test.txt
copied file exits: true
bytes copied: 11
copied file size: 11
package com.logicbig.example.files;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CopyExample3 {
public static void main(String... args) throws IOException {
Path source = Files.createTempFile("copy-test-src-fle", ".txt");
Files.write(source, "some test content".getBytes());
System.out.println("Source file: " + source);
System.out.println("Source file size: " + Files.size(source));
//An outputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//copying now
long bytesCopied = Files.copy(source, outputStream);
System.out.println("Bytes copied: " + bytesCopied);
System.out.println("Content copied: " + new String(outputStream.toByteArray()));
}
}
Output
Source file: C:\Users\Joe\AppData\Local\Temp\copy-test-src-fle2624743003689332921.txt
Source file size: 17
Bytes copied: 17
Content copied: some test content