How To Rename A Folder In Java - java

how to rename a file in java . I am trying some codes, But it can rename file and not a folder , i want to rename the folder which has like 200 or 300 files in it . Can anyone help me in this ?

The following example renames the directory “test” to “dist” in the current directory:
File sourceFile = new File("test");
File destFile = new File("dist");
if (sourceFile.renameTo(destFile)) {
System.out.println("Directory renamed successfully");
} else {
System.out.println("Failed to rename directory");
}

Search for java rename folder and you will get plenty of examples.
For example try this:
It checks if the dirPath is a directory and renames it to the given name.
File dir = new File(dirPath);
if (!dir.isDirectory()) {
System.err.println("There is no directory # given path");
} else {
System.out.println("Enter new name of directory(Only Name and Not Path).");
String newDirName = scanner.nextLine();
File newDir = new File(dir.getParent() + "\\" + newDirName);
dir.renameTo(newDir);
}
How to rename the folder in java

Related

Validate Excel file is downloaded in Selenium Web driver Java

I'm able to download excel file by clicking Download button which comes under DOM ,
after that i want verify downloaded file is same one.
AUTO IT is not allowed in project.
I have tried below code for verification on local but if i will push this code to repo.
then user path will get change and code will fail.
`String filepath = "C:User\\Dhananjay\\Downloads";
String fileName = "report.xlsx"
File targetFile = new File(fileName,filePath);
if(! targetFile.exists())'
{
system.out.println("File is verified")`
}else{
system.out.println("file not downloaded")
}'
String userProfile = System.getProperty("user.home"); returns %USERPROFILE% variable.
So you can use String filepath = System.getProperty("user.home") + "\\Downloads";
Works even on Linux.
I have found way to validate on local path and it's generic one
File folder = new File(System.getProperty("user.home") +\\Downloads);
File[] listOfFiles = folder.listFiles();
boolean found = false;
File f = null;
for (File listOfFile : listOfFiles) {
if (listOfFile.isFile()) {
String fileName = listOfFile.getName();
System.out.println("File " + listOfFile.getName());
if (fileName.matches("5MB.zip")) {
f = new File(fileName);
found = true;
}
}
}
Assert.assertTrue("Downloaded document is not found",found );
f.deleteOnExit();

Cannot extract jar file in java application packaged for windows

My program was created in Netbeans 8.0.2. The program is supposed to create a (database) folder after installation and extract the contents of a (database) jar file from its library. The folder gets created quite okay, but the contents of the jar file do not get extracted.
How can I get the extraction of the jar file to work?
NB: When I run the program in Netbeans, everything goes well.
Sample Code:
String appHomeDir = new java.io.File(".").getCanonicalPath();
String destDir = appHomeDir + "/database";
File folder = new File(destDir);
if (!folder.exists()) {
folder.mkdir();
String current = new java.io.File(".").getCanonicalPath();
String jarFile = current + "\\app\\lib\\database.jar";
java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile);
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
if (file.isDirectory()) { // if its a directory, create it
f.mkdir();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (is.available() > 0) { // write contents of 'is' to 'fos'
fos.write(is.read());
}
fos.close();
is.close();
}
}
So the "database" directory gets created but the contents of "database.jar" do not get extracted.
Problem solved: I replaced "/app/lib/database.jar" with "/lib/database.jar"

how to delete the same file which is uploaded in a directory?

there is folder temp to which the files uploaded by users are stored. the file name is same for each user but the content is different. Each user uploads a file called abc.xlsx. now when "A" user uploads abc.xlsx file after processing that file should be deleted. But currently i am deleting all the files in the folder. which is a problem since one more user might be uploading the file ehich will be cleared too. So i was thinking of renaming the file by appending the username to the file and then delete that particular file.
This is the file upload:
ProcessForm uploadForm = (ProcessForm)form;
String folderpath = "servers/temp";
String filePath = folderpath + "/" + uploadForm.getUploadedFile().getFileName();
This will delete all the files in the folder:
String tempPath = folderpath;
File file = new File(tempPath);
File[] files = file.listFiles();
for (File f:files)
{
if (f.isFile() && f.exists())
{
f.delete();
}
}
I think i got it. This is working as expected:
String folderpath = "servers/temp";
String filePath = folderpath + "/" + "abc_"+user.getUsername()+".xlsx";
outputStream = new FileOutputStream(new File(filePath));
outputStream.write(uploadForm.getUploadedFile().getFileData());
Code to delete file:
File file = new File(filePath);
boolean fileDelete = file.delete();
if (fileDelete)
{
mLogger.debug("successfully deleted");
} else {
mLogger.error("cant delete a file");
}

I can't locate files which created by program

I created a desktop project in netbeans, in the project folder I have three files : file.txt, file2.txt and file3.txt, in the load of the program I want to call these three files, and this is the code I tried :
public void run() {
Path path = Paths.get("file.txt");
Path path2 = Paths.get("file2.txt");
Path path3 = Paths.get("file3.txt");
if(Files.exists(path) && Files.exists(path2) && Files.exists(path3)) {
lireFichiers();
}else{
JOptionPane.showConfirmDialog(null, "Files didn't found !");
}
}
but when I run my program I get the message : "Files didn't found !" which means he didn't found those files.
those files are created by this code :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
The following three lines will only create file handlers for your program to use. This will not create a file by itself. If you are using the handler to write it will also create a file for you provided you close correctly after writing.
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
So, a sample code will look like:
File file = new File("Id.txt");
FileWriter fw = new FileWriter(file);
try
{
// write to file
}
finally
{
fw.close();
}
If the file is in the root of your project, this should work:
Path path = Paths.get("foo.txt");
System.out.println(Files.exists(path)); // true
Where exatlcy are the files you want to open in your project?
Please specify the language you use.
Generally you could search the file to see whether the files are in the program bootup folder. For webapps you should pay attention to the "absolute path and the relative path".
=========Edit============
If you are using Jave, then the file should be write out using FileWriter.close() before you can find them in your hard disk.
Ref
Thank you all for your help, I just tried this :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
if(file.exists() && file2.exists() && file3.exists()){
// manipulation
}
and it works

Move inside a particular directory without knowing its name

I want to move inside a directory in Java but I don't know its name? Does Java provide any functionality to do so?
File srcFile = "C:/Entertainment/XXXXXXX/break.avi"
I am certain that there is only one directory inside Entertainment but I don't know its name. How can I move inside XXXXXXX directory to access any file inside it?
Any help?
Try,
File file = new File("C:/Entertainment");
File[] files = file.listFiles();
File srcDir = new File("C:/Entertainment/");
File srcFile = null;
for (File dirMember : srcDir.listFiles()) {
if (!dirMember.isDirectory()) {
continue; // we don't need regular files
}
if (dirMember.getName().equals(".")) {
continue; // we don't need this directory
}
if (dirMember.getName().equals("..")) {
continue; // we don't need the parent directory
}
// This is the one you need.
srcFile = new File(new File(srcDir, dirMember.getName()), "break.avi");
}
You could also use a FileFilter, e.g one from Commons IO
File dir = new File("C:/Entertainment/");
File[] files = dir.listFiles( DirectoryFileFilter.INSTANCE ); // returns all subdirs
srcFile = new File(files[0], "break.avi");
File srcFile = new File("C:\\Entertainment");
srcFile = new File(srcFile, srcFile.list()[0]);
srcFile = newFile(srcFile, "break.avi");
System.out.println(srcFile.getPath());
File outer= new File("C:/test");
File inner = outer.listFiles()[0];//if you are sure there is one
File[] listOfFilesInInnerMost = inner.listFiles();
System.out.println("Files: " + Arrays.asList(listOfFilesInInnerMost));
will print
Files: [C:\test\something\text (2).txt, C:\test\something\text (3).txt, C:\test\something\text.txt]

Categories

Resources