How to rename file java ? - java

I'm trying to rename files in a folder. But instead all of them get deleted
File thisFolder = new File("C:\\ . . . ");
File [] filesArray = thisFolder.listFiles();
int filesArrayLength = filesArray.length;
if (filesArray != null) {
for (int i = 0; i < filesArrayLength; i++) {
filesArray[i].renameTo(new File("test" + i + ".pdf"));
}
}
What am i doing wrong ? Why do all of the files get deleted instead of renamed

As #Pshemo pointed out you might be moving the file to the current directory. Try doing this instead. This will tell it to create the file under the given parent directory:
filesArray[i].renameTo(new File(thisFolder, "test" + i + ".pdf"));//thisFolder is your parent directory

String strFilePath= "C:/Users/";
public void renameFile(String strOldFileName, String strNewFileName) {
File oldName = new File(strFilePath + "/" + strOldFileName);
File newName = new File(strFilePath + "/" + strNewFileName);
if (oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}

Code example for you to rename the List of files in a given directory as below,
Suppose C:\Test\FileToRename isthe folder, the files which are listed under that has been renamed to test1.pdf,test2.pdf... etc..
File folder = new File("\\Test\\FileToRename");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File("c:\\Test\\FileToRename\\"+listOfFiles[i].getName());
f.renameTo(new File("c:\\Test\\FileToRename\\"+"test"+i+".pdf"));
}
}

Related

How to increment the filename number if the file exists

How can I increment the filename if the file already exists?
Here's the code that I am using -
int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
if (file.exists()) {
save = at.getText().toString() + num + ".jpg";
file = new File(myDir, save);
num++;
}
This code works, but only two files are saved, like file.jpg and file2.jpg.
This problem is to always initialize num = 0, so if file exists, it saves file0.jpg and does not check whether file0.jpg exists.
So, to code work. You should check until it is available:
int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
while(file.exists()) {
save = at.getText().toString() + (num++) + ".jpg";
file = new File(myDir, save);
}
Try this:
File file = new File(myDir, at.getText().toString() + ".jpg");
for (int num = 0; file.exists(); num++) {
file = new File(myDir, at.getText().toString() + num + ".jpg");
}
// Now save/use your file here
In addition to the first answer, I made some more changes:
private File getUniqueFileName(String folderName, String searchedFilename) {
int num = 1;
String extension = getExtension(searchedFilename);
String filename = searchedFilename.substring(0, searchedFilename.lastIndexOf("."));
File file = new File(folderName, searchedFilename);
while (file.exists()) {
searchedFilename = filename + "(" + (num++) + ")" + extension;
file = new File(folderName, searchedFilename);
}
return file;
}
int i = 0;
String save = at.getText().toString();
String filename = save +".jpg";
File f = new File(filename);
while (f.exists()) {
i++;
filename =save+ Integer.toString(i)+".jpg";
f = new File(filename);
}
f.createNewFile();
You can avoid the code repetition of some of the answers here by using a do while loop
Here's an example using the newer NIO Path API introduced in Java 7
Path candidate = null;
int counter = 0;
do {
candidate = Paths.get(String.format("%s-%d",
path.toString(), ++counter));
} while (Files.exists(candidate));
Files.createFile(candidate);
Kotlin version:
private fun checkAndRenameIfExists(name: String): File {
var filename = name
val extension = "pdf"
val root = Environment.getExternalStorageDirectory().absolutePath
var file = File(root, "$filename.$extension")
var n = 0
while (file.exists()) {
n += 1
filename = "$name($n)"
file = File(root, appDirectoryName + File.separator + "$filename.$extension")
}
return file
}
Another simple logic solution to get the unique file name under a directory using Apache Commons IO using WildcardFileFilter to match the file name and get the number of exists with the given name and increment the counter.
public static String getUniqueFileName(String directory, String fileName) {
String fName = fileName.substring(0, fileName.lastIndexOf("."));
Collection<File> listFiles = FileUtils.listFiles(new File(directory), new WildcardFileFilter(fName + "*", IOCase.INSENSITIVE), DirectoryFileFilter.DIRECTORY);
if(listFiles.isEmpty()) {
return fName;
}
return fName.concat(" (" + listFiles.size() + ")");
}
This is the solution I use to handle this case. It works for folders as well as for files.
var destination = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyFolder")
if (!destination.exists()) {
destination.mkdirs()
} else {
val numberOfFileAlreadyExist =
destination.listFiles().filter { it.name.startsWith("MyFolder") }.size
destination = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"MyFolder(${numberOfFileAlreadyExist + 1})"
)
destination.mkdirs()
}
Having needed to solve this problem in my own code, I took Tejas Trivedi's answer, made it work like Windows when you happen to download the same file several times.
// This function will iteratively to find a unique file name to use when given a file: example (###).txt
// More or less how Windows will save a new file when one already exists: 'example.txt' becomes 'example (1).txt'.
// if example.txt already exists
private File getUniqueFileName(File file) {
File originalFile = file;
try {
while (file.exists()) {
String newFileName = file.getName();
String baseName = newFileName.substring(0, newFileName.lastIndexOf("."));
String extension = getExtension(newFileName);
Pattern pattern = Pattern.compile("( \\(\\d+\\))\\."); // Find ' (###).' in the file name, if it exists
Matcher matcher = pattern.matcher(newFileName);
String strDigits = "";
if (matcher.find()) {
baseName = baseName.substring(0, matcher.start(0)); // Remove the (###)
strDigits = matcher.group(0); // Grab the ### we'll want to increment
strDigits = strDigits.substring(strDigits.indexOf("(") + 1, strDigits.lastIndexOf(")")); // Strip off the ' (' and ').' from the match
// Increment the found digit and convert it back to a string
int count = Integer.parseInt(strDigits);
strDigits = Integer.toString(count + 1);
} else {
strDigits = "1"; // If there is no (###) match then start with 1
}
file = new File(file.getParent() + "/" + baseName + " (" + strDigits + ")" + extension); // Put the pieces back together
}
return file;
} catch (Error e) {
return originalFile; // Just overwrite the original file at this point...
}
}
private String getExtension(String name) {
return name.substring(name.lastIndexOf("."));
}
Calling getUniqueFileName(new File('/dir/example.txt') when 'example.txt' already exists while generate a new File targeting '/dir/example (1).txt' if that too exists it'll just keep incrementing number between the parentheses until a unique file is found, if an error happens, it'll just give the original file name.
I hope this helps some one needing to generate a unique file in Java on Android or another platform.
This function returns the exact new file with an increment number for all kind of extensions.
private File getFileName(File file) {
if (file.exists()) {
String newFileName = file.getName();
String simpleName = file.getName().substring(0, newFileName.indexOf("."));
String strDigit = "";
try {
simpleName = (Integer.parseInt(simpleName) + 1 + "");
File newFile = new File(file.getParent() + "/" + simpleName + getExtension(file.getName()));
return getFileName(newFile);
}
catch (Exception e){
}
for (int i=simpleName.length()-1; i>=0; i--) {
if (!Character.isDigit(simpleName.charAt(i))) {
strDigit = simpleName.substring(i + 1);
simpleName = simpleName.substring(0, i+1);
break;
}
}
if (strDigit.length() > 0) {
simpleName = simpleName + (Integer.parseInt(strDigit) + 1);
}
else {
simpleName += "1";
}
File newFile = new File(file.getParent() + "/" + simpleName + getExtension(file.getName()));
return getFileName(newFile);
}
return file;
}
private String getExtension(String name) {
return name.substring(name.lastIndexOf("."));
}

Code for finding the files numbers missing in a folder

I need to identify the file numbers which are missing in a folder.
I have retrieved the files names by using the code below :
File folder = new File(FILE_PATH);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
But now after retrieving i need to find which are the file number which are missing from a file range of 1-1976 both included.
If you need just the filenames, you may use list() method. After you get all the filenames with this method, you can just check the presence of the specified filenames, like:
File parent = ...
String prefix = "xxx_", suffix = ".txt"; // for example
Set<String> files = new HashSet<>(Arrays.asList(parent.list()));
// or, as suggested by #JulienLopez:
String pattern = Pattern.quote(prefix) + "\\d+" + Pattern.quote(suffix);
Set<String> files = new HashSet<>(Arrays.asList(parent.list((dir, file) -> file.matches(pattern))));
for (int i = 1; i <= 1976; ++i) { // actually constant should be used
if (!files.contains(prefix + i + suffix)) {
System.out.format("File #%d doesn't exist%n", i);
}
}
But if you really need to check, that the file is not, for example, the directory, there's one more way to do it, by just creating the Files for every i and checking its existence:
for (int i = 1; i <= 1976; ++i) {
File file = new File(parent, prefix + i + suffix);
if (!file.isFile()) {
System.out.format("File #%d doesn't exist or is directory%n", i);
}
}
I'm not sure your structural of your file name , and what exactly on your mind with "both included". That is my idea,I hope it's a bit help for you.
String FILE_PREFIX= "your_file_prefix"; // Your file prefix. If your file is "logfile_on_20160121_0001" then the prefix is "logfile_on_20160121_"
int RANGE_MIN = 1;
int RANGE_MAX = 1976;
int fileList[] = new int[RANGE_MAX];
int directoryList[] = new int[RANGE_MAX];
// Quote your code with a bit modify from me
File folder = new File(FILE_PATH);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
// Added started
String tempSplitedName[] = listOfFiles[i].split(FILE_PREFIX);
if(tempSplitedName.length==2){
int seq = Integer.parseInt(tempSplitedName[2]);
if(seq>=RANGE_MIN && seq<=RANGE_MAX){
fileList[seq] = 1;
}
}
// Added ended
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
// Added started
String tempSplitedName[] = listOfFiles[i].split(FILE_PREFIX);
if(tempSplitedName.length==2){
int seq = Integer.parseInt(tempSplitedName[2]);
if(seq>=RANGE_MIN && seq<=RANGE_MAX){
directoryList[seq] = 1;
}
}
// Added ended
}
// Now you count missing files/directory, which is equal 0
for (int i=RANGE_MIN; i<=RANGE_MAX; i++){
if(fileList[i]==0) System.out.println("Missing file No." + i);
}
for (int i=RANGE_MIN; i<=RANGE_MAX; i++){
if(directoryList[i]==0) System.out.println("Missing directory No." + i);
}

File isDirectory() method always returns false when folder name contains special chars

I always get a false return from isDirectory() method when the folder name contains specials chars like ó or ñ.
The Java code works fine in DOS, I have the problem executing jar in my NAS (Linux).
public static void listarDirectorio(File f, String separador)
throws Exception {
File[] ficheros = f.listFiles();
File ficheroTratado = null;
for (int x = 0; x < ficheros.length; x++) {
ficheroTratado = null;
ficheroTratado = ficheros[x].getCanonicalFile();
if (!ficheroTratado.isDirectory()) {
System.out.println(
"Checking file: " + ficheroTratado.getName());
if (esBorrable(ficheroTratado.getName())) {
System.out.println(
"File can be erased: " + ficheroTratado.getName());
}
}else if (!ficheros[x].getName().startsWith("#")) {
String nuevo_separador;
nuevo_separador = separador + " # ";
listarDirectorio(ficheros[x], nuevo_separador);
}
}
}

See the list of the files in an external storage

I wanted to see all the files I have in my external storage, I have this library that display the text to the user, but when I'm using it to show the sub files, it says something like :
(Ljava.File;# How do I get it to show the name of the actual files to the user? Also, how can I show the name for a specific folder to the user? say file #3?
File[] files = myDir.listFiles();
UIHelper.displayText(this, R.id.textView1, files.toString());
Checl if sdcard is mounted or not.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
///mounted
}
Get the path of sd card
File dir= new File(android.os.Environment.getExternalStorageDirectory());
Then call
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();//contains list of all files ending with
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {// if its a directory need to get the files under that directory
walkdir(listFile[i]);
} else {// add path of files to your arraylist for later use
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
This is the code for printing list of files and folders from ExternalStorage
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
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++)
{
Log.d("Files", "FileName:" + file[i].getName());
}
Don't forget to put below permission in you android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can use a recursive method to scan all your SD card:
String sdCardState = Environment.getExternalStorageState();
if( !sdCardState.equals(Environment.MEDIA_MOUNTED ) ) {
//displayMessage("No SD Card.");
return;
} else {
File root = Environment.getExternalStorageDirectory();
lookForFilesAndDirectories(root);
}
// lookForFilesAndDirectories() method:
public void lookForFilesAndDirectories(File file) {
if( file.isDirectory() ) {
String[] filesAndDirectories = dir.list();
for( String fileOrDirectory : filesAndDirectories) {
File f = new File(dir.getAbsolutePath() + "/" + fileOrDirectory);
lookForFilesAndDirectories(f);
}
} else {
doSomethingWithFile(f);
}
}

Prevent Dir deleting

the following code is deleting files and DIRS in a specific folder.
How could I adjust it, so it will delete only the files in the folder but not the dirs inside
code:
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
thanks,
ray.
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
if( !listOfFiles[i].isDirectory() ){ // if not a directory...
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
}
Make sense? :)
Easy ...
if (!listOfFiles[i].isDirectory()) {
listOfFiles[i].delete();
}
FWIW - your current code will only delete empty subdirectories. According to the javadoc, deleting a directory that is non-empty will fail; i.e. return false.
You have to use File.isDirectory
if(!listOfFiles[i].isDirectory())
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
http://download.oracle.com/javase/6/docs/api/java/io/File.html#isDirectory()
if (!listOfFiles[i].isDirectory()) { listOfFiles[i].delete(); }

Categories

Resources