WAP to replace the name of a file with special character instead of spaces in Java
File handling is a key topic in Java. You’ll be asked a lot of questions about this during your interview. I answered a few of the interview questions about file handling, including how to compare two text files, how to set file permissions, how to add text to a file, how to count characters, words, and lines in a text file, and how to find the words that appear the most frequently in a text file. Here you can find more file management software. From there, we’ll discover in this tutorial how to list all files in a directory in Java using some simple examples and java 8 code.
Lets say I have a folder with the different files as shown in the below image and I want to replace the spaces in the name of a file with special character (-) instead.
import java.io.File;
public class BehindJavaFileOps {
public static void main(String[] args) {
// Creating a File object for directory
File directoryPath = new File("E:\\Studies\\2 semester\\273 Hack Tricks");
// List of all files and directories
File filesList[] = directoryPath.listFiles();
System.out.println("List of files and directories in the specified directory:");
System.out.println(" ");
for (File file : filesList) {
String ss = file.getName();
char ch = '-';
ss = ss.replace(' ', ch).toLowerCase().replace(".txt", "");
System.out.println("String after replacing spaces with given character: " + ss);
}
}
}
Output:
List of files and directories in the specified directory:
String after replacing spaces with given character: 10-reasons-why-pcs-crash-u-must-know
String after replacing spaces with given character: 10-security-enhancements
String after replacing spaces with given character: 20-great-google-secrets
String after replacing spaces with given character: 250-tech-books-online
String after replacing spaces with given character: 36-graphics-&-design-ebooks
String after replacing spaces with given character: a-basic-guide-to-the-internet
String after replacing spaces with given character: a-basic-unix-overview.rtf