Ik wil een bestand van de ene locatie naar een andere locatie in Java kopiëren. Wat is de beste manier om dit te doen?
Dit is wat ik tot nu toe heb:
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
public static void main(String[] args) {
File f = new File(
"D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
List<String>temp=new ArrayList<String>();
temp.add(0, "N33");
temp.add(1, "N1417");
temp.add(2, "N331");
File[] matchingFiles = null;
for(final String temp1: temp){
matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(temp1);
}
});
System.out.println("size>>--"+matchingFiles.length);
}
}
}
Hiermee wordt het bestand niet gekopieerd, wat is de beste manier om dit te doen?
Antwoord 1, autoriteit 100%
U kunt ditgebruiken (of een andere variant):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Ik raad ook aan om File.separator
of /
te gebruiken in plaats van \\
om het compatibel te maken voor meerdere besturingssystemen, vraag/ antwoord op deze hier.
Omdat je niet zeker weet hoe je bestanden tijdelijk moet opslaan, bekijk je ArrayList
:
List<File> files = new ArrayList();
files.add(foundFile);
Om een List
met bestanden naar een enkele map te verplaatsen:
List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
Files.copy(file.toPath(),
(new File(path + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
Antwoord 2, autoriteit 64%
Stream gebruiken
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();
}
}
Kanaal gebruiken
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-lib gebruiken:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Java SE 7 Files-klasse gebruiken:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Of probeer Googles Guava:
https://github.com/google/guava
documenten:
https://guava.dev/releases /snapshot-jre/api/docs/com/google/common/io/Files.html
Tijd vergelijken:
File source = new File("/Users/sidikov/tmp/source.avi");
File dest = new File("/Users/sidikov/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/sidikov/tmp/sourceChannel.avi");
dest = new File("/Users/sidikov/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/sidikov/tmp/sourceApache.avi");
dest = new File("/Users/sidikov/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/sidikov/tmp/sourceJava7.avi");
dest = new File("/Users/sidikov/tmp/destJava7.avi");
start = System.nanoTime();
copyFileUsingJava7Files(source, dest);
System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));
Antwoord 3, Autoriteit 6%
Gebruik de nieuwe Java-bestandslessen in Java & GT; = 7.
Maak de onderstaande methode en importeer de benodigde libs.
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Gebruik de gemaakte methode zoals hieronder in de main:
File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);
try {
copyFile(dirFrom, dirTo);
} catch (IOException ex) {
Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}
NB: – Filefrom is het bestand dat u wilt kopiëren naar een nieuwe bestandsfilet in een andere map.
Credits – @scott: Standaard beknopt manier om een bestand in Java te kopiëren?
Antwoord 4, Autoriteit 5%
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
Antwoord 5
Files.exists()
Files.createDirectory()
Files.copy()
Bestaande bestanden overschrijven:
Files.move()
Files.delete()
Files.walkFileTree()
voer hier de linkbeschrijving in
Antwoord 6
U kunt het doen met de Java 8 Streaming API, PrintWriteren de Files API
try (PrintWriter pw = new PrintWriter(new File("destination-path"), StandardCharsets.UTF_8)) {
Files.readAllLines(Path.of("src/test/resources/source-file.something"), StandardCharsets.UTF_8)
.forEach(pw::println);
}
Als u wilt wijzigen de inhoud On-the-Fly tijdens het kopiëren , bekijk deze link voor het uitgebreid voorbeeld https://overflowed.dev/blog/copy-file-and-modify-with-java-streams /
Antwoord 7
Kopieer een bestand van de ene locatie naar een andere locatie, hoeft de hele inhoud naar een andere locatie te kopiëren. Files.copy(Path source, Path target, CopyOption... options) throws IOException
This Methode verwacht de bronlocatie die originele bestandslocatie en doellocatie is die een nieuwe maplocatie is met hetzelfde type bestand (als origineel).
Ofwel de doellocatie moet in ons systeem bestaan, anders moeten we een maplocatie maken en vervolgens in die maplocatie moeten we een bestand maken met dezelfde naam als originele bestandsnaam. Den met behulp van kopieerfunctie kunnen we eenvoudig een bestand van één locatie kopiëren naar andere.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}