Rename all files in a folder using java [duplicate] - java

This question already has answers here:
Rename a file using Java
(15 answers)
Closed 8 years ago.
How can we rename all files in a folder using java?
C:/temp/pictures/1.jpg
C:/temp/pictures/2.jpg
C:/temp/pictures/3.jpg
C:/temp/pictures/4.jpg
C:/temp/pictures/5.jpg
Rename to
C:/temp/pictures/landscape_1.jpg
C:/temp/pictures/landscape_2.jpg
C:/temp/pictures/landscape_3.jpg
C:/temp/pictures/landscape_4.jpg
C:/temp/pictures/landscape_5.jpg
Kind regards

Take a look at below code which check file in the folder and rename it.
File dir = new File("D:/xyz");
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles()) {
try {
File newfile =new File("newfile.txt");
if(f.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I Hope It Will Help You

Related

java.io.IOException- can't create file in build folder [duplicate]

This question already has answers here:
File loading by getClass().getResource()
(2 answers)
How to use SQLite database inside jar file?
(4 answers)
Where should I place my sqlite database in my java maven project
(1 answer)
Closed 8 months ago.
Java project build by Gradle.
I want to create file in \build\resources\main\db\sqlite\insert-data.sql
I try this:
protected File getDestinationFile(String baseDir) {
try {
URL testURL = ClassLoader.getSystemClassLoader().getResource("db/sqlite");
String pathName = testURL + "/" + DEFAULT_FILE_NAME_INSERT_DATA;
logger.debug("pathName = " + pathName);
File newFile = new File(pathName);
newFile.createNewFile();
return newFile;
} catch (IOException e) {
logger.error(e.getMessage(), e);
return null;
}
}
But I get error on runtime:
[17.06.2022 00:19:38.223] MyClass.getDestinationFile(SQLiteStrategy.java:170) ERROR:
java.io.IOException:
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)

How can I recursively FTP a directory structure using Jsch? [duplicate]

This question already has answers here:
Transfer folder and subfolders using ChannelSftp in JSch?
(3 answers)
Closed 5 years ago.
I'm trying to traverse a directory and upload all contents and directories in the same structure.
This is an example structure:
Dir1/
....Dir1_1/
....Dir1_2/
........Dir1_2_1/
............file.txt
Dir2/
....file.txt
....file2.txt
Dir3/
Dir4/
index.html
index.css
example.file
I've tried the following:
private void ftpFiles(File[] files, ChannelSftp channelSftp) throws SftpException, FileNotFoundException {
for (File file : files) {
System.out.println("Uploading: " + file.getName());
if (file.isDirectory()) {
System.out.println(file.getName() + " is a directory");
SftpATTRS attrs;
try {
channelSftp.stat(file.getName());
} catch (Exception e) {
System.out.println(file.getName() + " does not exist. Creating it...");
channelSftp.mkdir(file.getName());
}
channelSftp.cd(file.getName());
this.ftpFiles(file.listFiles(), channelSftp);
} else {
channelSftp.put(new FileInputStream(file), file.getName());
}
}
}
I'm taking an array of top level files, and recursively going down each one.
The problem is once I hit the first directory and cd into it, all further files and directories are inside of this.
Example: /Dir1/Dir1_1/Dir1_2/Dir1_2_1/Dir2/Dir3/Dir4/...etc
How can I do a ../ with my channel while calling this recursively?
Maybe something like (pseudo code):
List<Files> directories = new ArrayList<> ();
if (file is directory) directories.add(file);
else dowloadFile();
for (File f : directories) {
cd(f);
ftpFiles(listFiles());
cd(..);
}

Files.newDirectoryStream(path) does not return files recursively [duplicate]

This question already has answers here:
Recursively list all files within a directory using nio.file.DirectoryStream;
(9 answers)
Closed 6 years ago.
I m expecting to see a list of all files located under path d:/test folder. However, I can only get the files directly under that folder, but not recursively.
Code:
String folder = "D:/test";
Path path = fs.getPath(folder);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
for (Path p : directoryStream) {
System.out.println(p.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}
result:
a.txt
folder
folder structure:
Another way to this extending your own logic :
public static void printFileNamesRecursively(String path){
Path yourPath = FileSystems.getDefault().getPath(path);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(yourPath)) {
for (Path p : directoryStream) {
System.out.println(p.getFileName());
if(p.toFile().isDirectory()){
printFileNamesRecursively(p.toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
The Files::newDirectoryStream are meant to behave like that. If you want to recursively retrieve all directories and files in the given directory and its sub-directories, you will need Files::walk or Files::walkFileTree. For example (I assume you use Java 8):
Path path = //...
try {
Files.walk(path).map(Path::getFileName).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
This is the right behavior for DirectoryStream. Instead, You can use org.apache.commons.io.FileUtils to enumerate the files recursively.

Java - How I can check if file is exist? [duplicate]

This question already has answers here:
How do I check if a file exists in Java?
(19 answers)
Closed 7 years ago.
I'm creating a file with writeToFile() function.
Before I call writeToFile() function, I want to check if the file already exist or not.
How can I do this?
code:
private void writeToFile(String data, String fileName) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(fileName, Context.MODE_APPEND));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
You could utilize java.io.File and call the .exists() method to check if the file exists.
Use the following code to check if a file already exists.
if(file.exists() && !file.isDirectory()) {
// continue code
}
Using java.io.File
File f = new File(fileName);
if (f.exists()) {
// do something
}
This is a duplicate.
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

NIO getParentFile().mkdir() [duplicate]

This question already has answers here:
Using Java nio to create a subdirectory and file
(3 answers)
Closed 8 years ago.
Is there a way to create a file and directory in one shot
as in below... (Using Java 7 and NIO... Paths and Files static methods ).
where you wouldn't have to type the Path and then file in separate lines ( of code ) ?
File file = new File("Library\\test.txt");
if (file.getParentFile().mkdir()) {
file.createNewFile();
} else {
throw new IOException("Failed to create directory " + file.getParent());
}
Basically looking for the equivalent approach to "getParentFile().mkdir()" off the Path ( and file ) entered in Java 7 NIO.
Thx
Actually realized it's accopmplished this way..
Path file = Paths.get("/Users/jokrasa/Documents/workspace_traffic/javaReviewFeb28/src/TEST/","testy.txt");
try {
Files.createDirectory(file.getParent());
Files.createFile(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So you don't have to type it in twice actually...
Cheers !

Categories