Copy Files Java - java

I'm trying to copy files using java. I have an arraylist of File objects that need copying but when the actual copy takes place the destination folder gets turned into a file and nothing is copied
System.out.println("Dest: " + destPath.toString());
ArrayList<File> fileList = listFiles(sourceDir);
for (File file : fileList) {
Path sourcePath = Paths.get(file.getPath());
System.out.print("\r\nSource: " + sourcePath.toString());
CopyOption[] options = new CopyOption[] {
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
try {
Files.copy(sourcePath, destPath, options);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
The printed paths are:
Dest: C:\Users\Ceri\Desktop\New folder (2)
Source: C:\Users\Ceri\Desktop\New folder\Blue cave floor.png
Source: C:\Users\Ceri\Desktop\New folder\New Text Document.txt
Basically when i'm doing is trying to get a list of all changed/new files in a directory - specified by a text field - and copy them to another directory - again specified by a text field
the listFiles method returns the files

The destination path needs to describe a file, if you wan't to copy a file.
Just add the filename to destPath.
Files.copy(sourcePath, destPath+"/"+file.getName(), options);

Source: C:\Users\Ceri\Desktop\New folder\Blue cave floor.png Source: C:\Users\Ceri\Desktop\New folder\New Text Document.txt
Make sure your slashes are correct first
If you are using backward slash, use \\
If you are using forward slash, use /
For example, change your paths to:
C:/Users/Ceri/Desktop/New folder/Blue cave floor.png
Or
C:\\Users\\Ceri\\Desktop\\New folder\\Blue cave floor.png
and try again.

one approach is to use Apache commons IO FilesUtils.
try {
Path fileToCopy = Paths.get("path-of-file-to-copy");
FileUtils.copyFile(fileToCopy.toFile(), new File("your-destination-path"));
} catch (IOException e) {
//handle
}
or the other approach is to use standard Java NIO Files.copy() method
try {
Path fileToCopy = Paths.get("path-of-file-to-copy");
Files.copy(fileToCopy, Paths.get("your-destination-path"));
} catch (IOException e) {
//handle
}

If you are using Apache Commons - there is a FileUtils class you could use to copy the whole directory
try {
FileUtils.copyDirectory(sourceDir, destPath);
} catch (IOException e) {
e.printStackTrace();
}

Related

Zipping folders together

so I am generating files and I need to zip them to create a "Resourcepack" for Minecraft.
So on the surface, it looks like the file zips perfectly fine, however I have found some very strange behaviour. In windows, if you zip the directory itself, minecraft will not accept the zip however if you zip the contents, it will work. By the looks of it, this code achieves the first, but I can't manage to find a way to do the latter. The SHA1 of the different Zips are different so there is something going on that I cant see. When viewed they are exactly the same contents.
the code:
public static void pack(String sourceDirPath, String zipFilePath){
sourceDirPath = getDataFolder().getAbsolutePath() + "/" + sourceDirPath;
zipFilePath = getDataFolder().getAbsolutePath() + "/" + zipFilePath;
try {
Path p = Files.createFile(Paths.get(zipFilePath));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
Path pp = Paths.get(sourceDirPath);
Files.walk(pp)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
Files.copy(path, zs);
zs.closeEntry();
} catch (IOException e) {
System.err.println(e);
}
});
}
}catch (IOException e){
e.printStackTrace();
}
}
EDIT:
I have looking at the properties of the contents of each zip and it looks like the correctly working one is indexing the files im still yet to find anything that allows me to do this

Using the Files.move creates a new "file" file type rather than moving the file to a directory

I am trying to make a program that extracts multiple MP4 files from there individual folders and places them in a folder that is already created (code has been changed slightly so that it doesn't mess up any more of the MP4s, rather dummy text files).
I have managed to get so far as to list all folders/files in the specified folder however am having trouble moving them to a directory.
static File dir = new File("G:\\New Folder");
static Path source;
static Path target = Paths.get("G:\\gohere");
static void showFiles(File files[]) {
for (File file : files) { // Loops through each file in the specified directory in "dir" variable.
if (file.isDirectory()) { // If the file is a directory.
File[] subDir = file.listFiles(); // Store each file in a File list.
for (File subFiles : subDir) { // Loops through the files in the sub-directory.
if (subFiles.getName().endsWith(".mp4")) { // if the file is of type MP4
source = subFiles.toPath(); // Set source to be the abs path to the file.
System.out.println(source);
try {
Files.move(source, target);
System.out.println("File Moved");
} catch (IOException e) {
e.getMessage();
}
}
}
} else {
source = file.toPath(); // abs path to file
try {
Files.move(source, target);
System.out.println("File moved - " + file.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
showFiles(dir.listFiles());
}
The problem is when I go to move the file from the source folder to the target, it removes or converts the target.
Files.move isn't like the command line. You're programming. You have to spell things out. You're literally asking Files.move to make it so that target (here, G:\GoHere) will henceforth be the location for the file you are moving. If you intended: No, the target is G:\GoHere\TheSameFileName then you have to program this.
Separately, your code is a mess. Stop using java.io.File and java.nio.Path together. Pick a side (and pick the java.nio side, it's an newer API for a good reason), and do not mix and match.
For example:
Path fromDir = Paths.get("G:\\FromHere");
Path targetDir = Paths.get(G:\\ToHere");
try (DirectoryStream ds = Files.newDirectoryStream(fromDir)) {
for (Path child : ds) {
if (Files.isRegularFile(child)) {
Path targetFile = targetDir.resolve(child.getFileName());
Files.move(child, targetFile);
}
}
}
resolve gives you a Path object that is what you need here: The actual file in the target dir.

Read files inside a folder from a path

I need to read all files inside a folder. Here's my path c:/records/today/ and inside path there are two files data1.txt and data2.txt. After getting the files, I need to read and display it.
I already did with the first file, I just don't know how to do both.
File file = ResourceUtils.getFile("c:/records/today/data1.txt");
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
Also, you can use this to check child paths isFile or directory
Arrays.stream(ResourceUtils.getFile("c:/records/today/data1.txt").listFiles())
.filter(File::isFile)
.forEach(file -> {
try {
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
});
Please try with
File file = ResourceUtils.getFile("c:\\records\\today\\data1.txt");
See https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
To read all the files in specific folder, you can do it somewhat like below:
File dir = new File("c:/records/today");
for (File singleFile: dir.listFiles()) {
// do file operation on singleFile
}
You can change the code slightly, and instead of using Resources.getFile use Files.walk to return a stream of files and iterate over them.
Files.walk(Paths.get("c:\\records\\today\)).forEach(x->{
try {
if (!Files.isDirectory(x))
System.out.println(Files.readAllLines(x));
//Add internal folder handling if needed with else clause
} catch (IOException e) {
//Add some exception handling as required
e.printStackTrace();
}
});

Is there a way to replace an html file with another one by coding in Java?

My purpose is to replace an html file in a folder by another one, so that at the end :
html_link1 will be replaced by html_link2
Is there a way to update HTML files by executing code in Java ?
public static void main(String[] args) {
Path sourceDirectory = Paths.get("C:/Users/Me/Desktop/project/adresse.url");
Path targetDirectory = Paths.get("C:/Users/Me/Desktop/project/adresse2.url");
//copy source to target using Files Class
try {
Files.copy(sourceDirectory, targetDirectory,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
I need to find a way to change the URL, since the Path are now the same, the URL of the second HTML file didn't changed
You have to pass the absolute file path untill and unless you wish to replace the whole directory.
Path sourceFilePath = Paths.get("C:/Users/Me/Desktop/project/adresse.url");
Path targetFilePath = Paths.get("C:/Users/Me/Desktop/project/adresse2.url");
try {
Files.copy(sourceFilePath , targetFilePath ,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println(e.toString());
}
So long as they actually files, and you have the proper permission for the directory they are in, then you can do this the same way you would for any file.

java.io.file backslash saving in weblogic's root

I have a java application running into a weblogic server.
The application have to write a file into the path \bla\john doe (for example).
For this, I used the java.io.File library to:
1. Verify if the path exists
2. If not, create it.
3. Verify if the file exists
4. if not, create it
5. Write the bytes into the file.
The correct behavior would be to create the directory bla into the root of the weblogic's current domain and then create a john doe inside it.
The problem is: in my current enviroment it works like a charm, but in the client's one, the application does not consider the backslash as an element of the path, and instead of creating two directories, the application only creates one, literally named as \bla\john does.
So, instead of:
-domain_root
-bla
-john does
I get the following:
-domain_root
-\bla\john does
(and if I escape it, occurres the same but with two backslash)
The odd is that if I use the commom slash (/bla/john doe), it works..
-domain_root
-bla
-john does
Does any one knows what possibly can be happening?
script for check the path
public File checkPath(String path) {
File f = new File(cls_Util.NeutralizeFilePath(path));
if (!(f.exists() && f.isDirectory())) {
try {
f.mkdirs();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for check the file:
public File checkFile(String path){
File f = new File(path);
return checkFile(f);
}
public File checkFile(File f) {
if (!(f.exists() && f.isFile())) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for create file
public File writeFile(String path, byte[] binaryfile) {
File file = checkFile(path);
if (file != null) {
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
try {
fos.write(binaryfile);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return file;
}
return null;
}
And to create the file:
String filePathPub = pathPub + newName;
File FilePathPub = writeFile(filePathPub, p_Arquivo);
On Windows the \ starts an absolute path; on Unix/Linux the backslash is a valid filename character (and therefore starts a relative path).
I would suggest you try to avoid using file name concatenation platform specific separators if you are not familiar with the semantic:
File current = new File();
File bla = new File(current, "bla");
(or simply stick to / (forward slash as used by Unix) to separate path components). Java translates this to the Windows character automatically).

Categories