Rename all folders in a directory - java

I need help in renaming all files and folders in a directory and add a character in front of there original name.
This is a method to rename a single folder:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);

So, something like:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
EDIT:
To change a file name, it might be more clear to add a temporary variable:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);

Go to the root folder and iterate over it. Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder.
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
Just check if this helps you.

Related

Java deleting folder and sub-folder 4th level

I want delete folder (directory) and sub-directory in JAVA, I need 2 conditions when there's file and where the folder is empty. I've been searched and trying all example I found, but not worked. Even when that code works, that just delete the file or just 1 folder (directory level 4) not all folder.
I want to delete old directory year\place\owner\month\file.
File source = new File("C:\\Users\\Workspaces\\projects\\uploadFolder\\year\\place\\owner\\month\\file");
Path sources = source.toPath();
I've tried this:
public static void rmdir(final File folder) {
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null){
for (int i = 0; i < list.length; i++){
File tmpF = list[i];
if (tmpF.isDirectory()) {
rmdir(tmpF); }
tmpF.delete();}
}
if (!folder.delete()){
System.out.println("can't delete folder : " + folder);}}
}
This:
public static void deleteDirectory(File path)
{
if (path == null)
return;
if (path.exists())
{
for(File f : path.listFiles())
{
if(f.isDirectory())
{
deleteDirectory(f);
f.delete();
}
else
{
f.delete();
}
}
path.delete();
}
}
This :
public static void deleteFiles (File file)
{
if(file.isDirectory())
{
File[] files = file.listFiles(); //All files and sub folders
for(int x=0; files != null && x<files.length; x++)
deleteFiles(files[x]);
file.delete();
}
}
This:
FileUtils.deleteDirectory(source);
This:
Files.delete(sources);

Appending string to destination to create new directory

Hello I am attempting to append some variables to a directory to create a new sub directory within the directory I am in but I am not sure how to do this, I know that .mkdir() allows me to create a new directory but I am not sure how I could append the variables and then create the new directory, here is my attempt so far:
package movefile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFile
{
static String newfile;
public static void main(String[] args)
{
File srcFolder = new File("/Users/francis/Desktop/folder1");
File destFolder = new File("/Users/francis/Desktop/folder2");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder (srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
FilenameFilter filter = new FilenameFilter()
{
#Override public boolean accept(File dir, String name)
{
return name.endsWith(".pdf");
}
};
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file); //needed for moving
//third attempt
File f = null;
File f1 = null;
String vendor;
String orderno;
String desc;
String v, v1, p;
boolean bool = false;
try {
f = new File("/Users/francis/Desktop/folder1/1234567898.pdf");
f1 = new File("/Users/francis/Desktop/folder2/");
v = f.getName();
v1 = f1.getName();
v = v.length() > 9 ? v.substring(0,8) : v;
p = "c3269";
vendor = "VendorName";
v = "file_" + p + " - " + v + ".pdf";
File destFile = new File(dest, v); //get dest and insert (append) project number so it creates new folder
copyFolder(srcFile,destFile);
File appendProject = new File("/Users/francis/Desktop/folder2/");
boolean successfull = appendProject.mkdir();
if (successfull)
{
System.out.println("New directory was created:");
}
else
System.out.println("Failed to create new directory");
bool = f.exists();
if(bool)
{
System.out.println("File name:" + v);
}
bool = f1.exists();
if (bool)
{
System.out.println("Folder name:" + v1);
}
}catch(Exception e){
e.printStackTrace();
}
}
}else{
//if file, then copy it
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
At the moment this is checking the folder for .pdf files appending P and V values to the name, trimming the string to 8 characters and moving the files into a new folder but I desire them to be moved and it creates new directory based on the project number which is located inside of the variable p.
Any help would be greatly appreciated, thanks a bunch!
Assuming you want to copy file File srcFile to folder File destDir you could do the following:
if( !destDir.exists() ) {
//create destDir and all missing parent folders
destDir.mkdirs(); //For simplicity I'll leave out the success checks, don't forget them in your code
}
String destFilename = srcFile.getName(); //adapt according to your needs
File destFile = new File( destDir, destFilename );
//You'd need to either implement that or use a library like Apache Commons IO
copy( srcFile, destFile );
If you want to create a directory from the filename first, do something like this:
String destSubDirName = makeDirName( destFilename ); //whatever you need to do here
File destSubDir = new File( destDir, destSubDirName );
destSubDir.mkdirs(); //again don't forget the checks
File destFile = new File (destSubDir, destFilename );
copy( srcFile, destFile );

Searching a directory for a file name

How to search a particular folder for a file name, that is input by the user. In my program the file is an excel spreadsheet. So if i basically use:
Scanner kbReader = new Scanner(System.in);
String fileName = kbReader.nextLine();
How would i search and open the corresponding file with the name fileName.
You need to use regular expression to match your file name like filename.matches("*"+expectedfilename+"*.xls")) on List of file names taken from directory.
String fileName = null;
File folder = new File("your/directory/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
fileName = listOfFiles[i].getName();
if(fileName.matches("*"+expectedfilename+"*.xls"))){ // put regex here
// do your code here and
// if you want to open do operation on file then file object
File file = listOfFiles[i];
}
}
}
Try this
File dir = new File("F:/");
File[] allFileName = dir.listFiles();
for (int i = 0; i < allFileName.length; i++) {
String filename = allFileName[i].getName()
if (allFileName[i].isFile()) {
if (filename.endsWith(".xls"))
System.out.println("This is a excel file with name " + filename);
}
}

Random File Access Java

I know there's a way to select a random file from a directory, but I don't know how it's coded in Java. I have pseudocode though. What I'm asking is if I could get a nudge in the right direction. My pseudocode is as follows:
dir = "directory";
String[] files = dir.listfiles();
String next = rand.nextInt(files.length);
Image img = next;
The reason I want to do it like this is because I have a long list of images that I would like to shuffle through.
Your pseudo code looks fine, you can get all the names recursively, store the names in an ArrayList, and randomly retrieve the names from the ArrayList as shown below:
static ArrayList<String> files = new ArrayList<String>();
public static void main(String[] args) {
File dir = new File(".");
getFileNames(dir);
Random rand = new Random();
String next = files.get(rand.nextInt(files.size()));
}
private static void getFileNames(File curDir) {
File[] filesList = curDir.listFiles();
for (File f : filesList) {
if (f.isDirectory())
getFileNames(f);
if (f.isFile()) {
files.add(f.getName());
}
}
}
You seem to be on the right track. Only thing is listFiles() returns a File[] not a String[]
Maybe try something like this
File file = new File(filename);
File[] files = new File[0]; // initialize
if (file.isDirectory()){
files = file.listFiles(); // populate
}
int fileIndex = new Random().nextInt(files.length); // get random index
Image img = new ImageIcon(files[fileIndex]).getImage(); // create image
Though the above may work, It's recommended using URL for embedded resources and not Files. Something like this
String[] filenames = file.list(); // list returns String
int fileIndex = new Random().nextInt(filenames.length);
Image img = null;
java.net.URL url = MyClass.class.getResource(filenames[fileIndex]);
if (url != null){
img = new ImageIcon(url).getImage();
} else {
img = null;
}
When using the class.gerResource(). The file will be searched for in the location of the class files. You can can also change the path a little bit, for example if you want a file structure like this
ProjectRoot
bin
MyClass.class
images
image1.png
image2.png
src
Then you can use this code
java.net.URL url = MyClass.class.getResource("images/" + filenames[fileIndex]);
Here is how I would implement your pseudo-code
private static final Random random = new Random(0x20131224 ^ // A seed value
System.currentTimeMillis()); // and more seed value(s).
public static File getRandomFile(String filePath) {
File f = new File(filePath); // Do we have a directory?
if (f == null || ! f.isDirectory()) {
return f;
}
File[] files = f.listFiles();
List<File> al = new ArrayList<File>();
for (File file : files) {
if (file != null && file.isFile() && file.canRead()) { // Make sure it's a file.
al.add(file);
}
}
return al.get(random.nextInt(al.size())); // Get a random file.
}
File filedir=new File("C:\\Users\\ramaraju\\Desktop\\japan02-12\\");
File[] files=filedir.listFiles();
Random generator = new Random();
int Low = 0;
int High = files.length;
int R = generator.nextInt(High-Low) + Low;
System.out.println(R);
for (int i = 0; i < files.length; i++) {
if(i==R)
{
System.out.println(files[i].getName());
}
}

Reading all files in a directory including its sub directories

This is how I set the path:
dPath = dPath.replace("\\", "/");
String iLen;
String FileName;
File iFolder = new File(dPath);
File[] listOfFiles = iFolder.listFiles();
When searching:
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
FileName = listOfFiles[i].getName();
for(String s : iEndsWith)
{
if(FileName.toLowerCase().endsWith(s))
{
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy h:mm aaa");
iLen = ReadableBytes(listOfFiles[i].length());
Object rowData[] = { FileName, listOfFiles[i].getAbsoluteFile(), sdf.format(listOfFiles[i].lastModified()), iLen };
iTableModel.addRow(rowData);
iTotalFiles ++;
}
}
}
}
That will only look for files in the given directory path, but not it's sub directories. How can I change that?
If you're on Java 7, you can use FileVisitor: http://docs.oracle.com/javase/tutorial/essential/io/walk.html
If not, just use a simple recursive version of your function.
Pass folder as Initial File which is to be searched
File foldr = new File("c:/javaFolder");
public void addFilesToList(File folder) {
File[] listofFiles = folder.listFiles();
if (listofFiles != null) {
for (File file : listofFiles) {
if (file.isFile()) {
} else
addFilesToList(file);
}
}
}
You can use DirectoryWalker from Apache Commons to walk through a directory hierarchy.

Categories

Resources