i'm trying to copy all the files inside a directory to another(but i want it to not copy the folders). I'm trying to use Files.copy but i'm getting this error:
Exception in thread "main" java.nio.file.FileAlreadyExistsException:
Here's my actual code:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Exercici1 {
public static void copiarArchivos(String pathSource,String pathOutcome, String sufix) throws IOException {
File origen = new File(pathSource);
String[] contenidoOrigen = origen.list();
for(String string:contenidoOrigen){
File interno = new File(origen,string);
if (interno.isDirectory()){
copiarArchivos(interno.getPath(),pathOutcome,sufix);
} else {
Path targetOutcome = Paths.get(pathOutcome);
Path targetSource = Paths.get(interno.getPath());
Files.copy(targetSource,targetOutcome);
}
}
}
public static void main(String[] args) throws IOException {
copiarArchivos("Vampiro_Mascarada","pruebaPDF",".pdf");
}
}
My folder structure is like this:
/out
/pruebasPDF
/src
/Vampiro_Mascarada
/1.pdf
/2.pfdf
/Images
/1.png
/2.png
You need to use to Files.copy(source,dest,CopyOption) with the REPLACE_EXISTING option.
Related
I created a Java program which basically moves all files within a specific "test" folder to a completely different and specific directory on the computer. How can I package the "test" folder, and both the java and class files into a single runnable JAR file?
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import javax.swing.JOptionPane;
public class Test
{
public static void main(String[] args) throws IOException
{
File sourceFolder = new File("test");
String dataFolder = System.getenv("APPDATA");
File destinationFolder = new File(dataFolder + "\\testing");
copyFolder(sourceFolder, destinationFolder);
}
private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException
{
if (sourceFolder.isDirectory())
{
if (!destinationFolder.exists())
{
destinationFolder.mkdir();
}
String files[] = sourceFolder.list();
for (String file : files)
{
File srcFile = new File(sourceFolder, file);
File destFile = new File(destinationFolder, file);
copyFolder(srcFile, destFile);
}
JOptionPane.showMessageDialog(null,"File installed successfully","Title",1);
}
else
{
Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
I get this error I get when I move the test folder:
Exception in thread "main" java.nio.file.NoSuchFileException: test
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileCopy.copy(WindowsFileCopy.java:98)
at java.base/sun.nio.fs.WindowsFileSystemProvider.copy(WindowsFileSystemProvider.java:283)
at java.base/java.nio.file.Files.copy(Files.java:1298)
at Test.copyFolder(test.java:39)
at Test.main(test.java:16)
On the first run, I want to copy the given File to a new location with a new file name.
Every subsequent run should overwrite the same destination file created during first run.
During first run, the destination file does not exist. Only the directory exists.
I wrote the following program:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
However, this throws null pointer exception on the following line:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
What am I missing?
Directory someDir is directly under my project's root directory in eclipse.
Both source files myFile.txt and myFile_Another.txt exists directly under my project's root directory in eclipse.
I used this and it works as I am expecting:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
Using Java nio.
Any idea why this works fine even on a Windows environment ?
Can you point me to some docs which explains why this works ?
I tried to look for it with no results.
package com.my.example;
import org.junit.Test;
import java.io.File;
public class TestPathCreation
{
#Test
public void testPathCreation() throws Exception {
final String path = "~/.my/dir";
System.out.println(path);
File f = new File(path);
System.out.println(f.mkdirs()); // true
}
}
I`m trying to import jcurses library to IntelliJ but get an error.
File -> Project Structure -> Modules -> import jar file.
Then in code:
import jcurses.widgets.Window;
class main {
public static void main(String[] args){
Window win = new Window(800, 600, true, "test");
win.setVisible(true);
}
Exception in thread "main" java.lang.ExceptionInInitializerError
at jcurses.system.InputChar.<clinit>(InputChar.java:25)
at jcurses.widgets.Window.<clinit>(Window.java:209)
at main.main(main.java:7)
Caused by: java.lang.RuntimeException: couldn't find jcurses library
at jcurses.system.Toolkit.getLibraryPath(Toolkit.java:121)
at jcurses.system.Toolkit.<clinit>(Toolkit.java:37)
Could someone point out where is my mistake?
Thanks in advance!
The answer is that dll must be in the same directory as jar file. Thanks to everyone!
Libray download url
https://sourceforge.net/projects/javacurses/files/javacurses/0.9.5/
The path of the library is in the root directory of the project
dynamically add the library
import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;
public class LoadLibrary {
public static void main(String cor[]) throws Exception {
// Cargando librerias necesarias
loadLibraryJCourses();
}
public static void loadLibraryJCourses() throws Exception{
loadDynamicLibrary(new File("lib/bin/jcourses/").getAbsolutePath(),"libjcurses64");
}
private static void addLibraryPath(String pathToAdd) throws Exception {
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
//get array of paths
final String[] paths = (String[]) usrPathsField.get(null);
//check if the path to add is already present
for (String path : paths) {
if (path.equals(pathToAdd)) {
return;
}
}
//add the new path
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
private static void loadDynamicLibrary(String pathLibraryDirectory, String libraryName) throws Exception{
File pathLibraryFile = new File(pathLibraryDirectory);
addLibraryPath(pathLibraryFile.getAbsolutePath());
System.loadLibrary(libraryName);
}
}
Sorry about readability. Stack appears to be trimming spaces from code lines & indents don't show up. Hrmph.
This was printing to the console without any problems...
CGT\whgdata\whnvp33.txt << EXPECTED OUTPUT (excerpt)
CGT\whgdata\whnvt30.txt
CGT\whgdata\whnvt31.txt
CGT\whgdata\whnvt32.txt
CGT\whgdata\whnvt33.txt
CGT\whgdef.txt
CGT\whgdhtml.txt
CGT\whibody.txt
etc....
...until I tried printing the hashtable to a file. Since that point, getFileListing isn't recognized as a valid symbol.
FileListing2.java:17: error: cannot find symbol
List<File> files = FileListing2.getFileListing(startingDirectory);
symbol: method getFileListing(File)
location: class FileListing2
1 error
Can someone lend a second set of eyes to help me uncover what I accidentally/overwrote. I'm sure it's something obvious. :\
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption.*;
import java.nio.file.Paths;
//
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
}
If your code is all you have for FileListing2, than there is no getFileListing() method for LileListing2, only a main() method
Yeah it IS something very obious, your class FileListing2 does not contain a method getFileListing(File). And it has to be static, the way you're trying to call it:
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
public static List<File> getFileListing(File f) {
/* implementation */
}
}