Read files inside a folder from a path - java

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();
}
});

Related

How to list the size of all files in directory recursively at once

I am trying to list the size of all files in directory similar to linux command du -a all at once recursively except in java. Instead of the file going through each file in the directory checking the size one at a time which takes more time
String directory = "
File[] parentfile;
parentfile = listFiles(directory);
for (File f:parentfile){
System.out.println(f.getSize());
}
You'll need to go through each file, but you can make it easy using Files.walk:
Path directory = Path.of("...");
try (Stream<Path> stream = Files.walk(directory)) {
long size = stream.filter(Files::isRegularFile)
.mapToLong(p -> {
try {
return Files.size(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
})
.sum();
}
The try-catch inside the mapToLong is necessary because Function doesn't allow checked exceptions.

FileUtils: Skips files that are already in destination and copy rest of the files

I am using the following method to transfer files between two directories using java.
FileUtils.copyDirectory(sourceDir, destinationDir,fileFilter,false);
But if a file with the same name is also found in the destination directory, the file from source overwrites it. What I want is to exclude those files which also exist in destination and copy rest of them, ultimately preventing overwriting..
One way is to write it yourself:
try (Stream<Path> files = Files.walk(sourceDir.toPath())
.filter(f -> fileFilter.accept(f.toFile()))) {
files.forEach(src -> {
Path dest = destinationDir.toPath().resolve(
sourceDir.toPath().relativize(src));
if (!Files.exists(dest)) {
try {
if (Files.isDirectory(src)) {
Files.createDirectories(dest);
} else {
Files.copy(src, dest,
StandardCopyOption.COPY_ATTRIBUTES);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
})
}
Or, you could just modify your filter:
FileFilter oldFilter = fileFilter;
fileFilter = f -> oldFilter.accept(f) &&
!Files.exists(destinationDir.toPath().resolve(
sourceDir.toPath().relativize(f.toPath())));

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.

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.

Copy Files 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();
}

Categories