The following Java code renames files but it does not rename the way I wanted it to. I want the rename files to start from beginning in the directory to the end per the “part” numbers (not the time it was added in inside a particular directory), but it does not do so. Is there an “if” check I can put, like: if filename.contains(j) then process this?
import java.io.File;
public class RenameFile2 {
public static void main(String[] args) {
String absolutePath1 = "1 to 4";
String absolutePath2 = "6 to 9";
String absolutePath3 = "10 to 99";
String absolutePath4 = "100 to 224";
File dir1 = new File(absolutePath1);
File dir2 = new File(absolutePath2);
File dir3 = new File(absolutePath3);
File dir4 = new File(absolutePath4);
File[] filesInDir1 = dir1.listFiles();
File[] filesInDir2 = dir2.listFiles();
File[] filesInDir3 = dir3.listFiles();
File[] filesInDir4 = dir4.listFiles();
int i1 = 1;
for(File file:filesInDir1) {
String name = file.getName();
String newName = "550 00510 00" + i1 + ".pdf";
String newPath = absolutePath1 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i1++;
}
int i2 = 6;
for(File file:filesInDir2) {
String name = file.getName();
String newName = "550 00510 00" + i2 + ".pdf";
String newPath = absolutePath2 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i2++;
}
int i3 = 10;
for(File file:filesInDir3) {
String name = file.getName();
String newName = "550 00510 0" + i3 + ".pdf";
String newPath = absolutePath3 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i3++;
}
int i4 = 100;
//int j = 99;
for(File file:filesInDir4) {
String name = file.getName();
/* if(name.contains(j))
{
}
*/
String newName = "550 00510 " + i4 + ".pdf";
String newPath = absolutePath4 + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
i4++;
}
}
}
In the documentation for .listFiles(), it says:
There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
You need to sort the array in the order you want to process them in a particular order.
Additional notes and suggestions:
String.contains() takes a String as an argument, not an int. You have this code commented out in your question.
Use the constructor for File to produce the new path instead of string concatenation: File newPath = new File(dir1, newName);
You need to sort the files once you list them, the listFiles() does not guarentee any order.
File[] filesInDir1 = dir1.listFiles();
Arrays.sort(filesInDir1);
You may need to implement a Comparator and call Arrays.sort(filesList, comparator) in order to have them custom sorted.
Once you have the files in sorted order, you can apply the rename logic as you wanted.
Another improvement would be, if you want to list only files with a pattern, you can filter while listing.
final String pattern = "regexpattern";
dir1.listFiles(new FilenameFilter(){
public boolean accept( File dir, String name ) {
return name.matches( pattern );
}
});
Related
I have a database connected that I am retrieving and storing local files and directories in. It works properly except when I run this segment, it will duplicate some of the results and store them. I believe the issue is in the way that I am grabbing them here, but I am not sure how to remedy it.
public static void Recursion(File dir, int dirid) {
for (java.io.File file : dir.listFiles()) {
if (file.isDirectory()) {
saveDir(dir, file);
} else if (file.isFile()) {
if (dirid == 0) {
saveDir(dir, file.getParentFile());
} // Begin Recursion, File
BoFile file1 = new BoFile();
file1.setFileName(file.getName());
file1.setFileType(file.getName().substring(file.getName().lastIndexOf('.') + 1).trim());
file1.setFileSize(new Long(file.length()).doubleValue() / 1024 + "MB");
file1.setFilePath(file.getPath());
file1.setDirNameId(dirid);
FileDAO fileDAO = new FileDAOImpl();
int id = fileDAO.insertFile(file1);
logger.info("New File: " + file.getName() + " ID = " + id);
}
}
}
private static void saveDir(File dir, File file) { // // Begin Recursion, Dir
Dir directory = new Dir();
directory.setDirName(file.getName());
directory.setDirNumberofFiles(dir.listFiles().length);
directory.setDirSize(new Long(dir.length()).doubleValue() / 1024 + "MB");
directory.setDirpath(dir.getPath());
DirDAO dirDAO = new DirDAOImpl();
int id = dirDAO.insertDir(directory);
logger.info("New Directory, " + file.getName() + " ID = " + id);
Recursion(file, id);
}
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("."));
}
building an Android app i came across the need to do some file copying. I would like a way to get new filenames in the event of a filename allready being used by adding a "(increment)" string in the filename. for example
text.txt ---> text(1).txt
The algorith should account for the following
1) if text.txt exists the new file name should NEVER be text.txt(1)
2) if text(1).txt exists then new filename should be text(2).txt not text(1)(1).txt
3) if text(1)foo.txt exists the new filename should be text(1)foo(1).txt
I've allready done the first but I'm having difficulties with the second. Regular expressions is not my strong suit!(It's not mandatory to use Regex. every approach is welcome) Some help ?
ANSWER:
combining my original code and one of the answers here I ended up with this which works very well for me in all cases regardless of file having an extension or not:
public static File getFinalNewDestinationFile(File destinationFolder, File fileToCopy){
String destFolderPath = destinationFolder.getAbsolutePath()+File.separator;
File newFile = new File(destFolderPath + fileToCopy.getName());
String filename=fileToCopy.getName();
String nameWithoutExtentionOrIncrement;
String extension = getFileExtension(filename);
if(extension!=null){
extension="."+extension;
int extInd = filename.lastIndexOf(extension);
nameWithoutExtentionOrIncrement = new StringBuilder(filename).replace(extInd, extInd+extension.length(),"").toString();
}
else{
extension="";
nameWithoutExtentionOrIncrement = filename;
}
int c=0;
int indexOfClose = nameWithoutExtentionOrIncrement.lastIndexOf(")");
int indexOfOpen = nameWithoutExtentionOrIncrement.lastIndexOf("(");
if(indexOfClose!=-1 && indexOfClose!=-1 && indexOfClose==nameWithoutExtentionOrIncrement.length()-1 && indexOfClose > indexOfOpen && indexOfOpen!=0){
String possibleNumber = nameWithoutExtentionOrIncrement.substring(indexOfOpen+1, indexOfClose);
try{
c = Integer.parseInt(possibleNumber);
nameWithoutExtentionOrIncrement=nameWithoutExtentionOrIncrement.substring(0, indexOfOpen);
}catch(Exception e){c=0;}
}
while(newFile.exists()){
c++;
String path = destFolderPath + nameWithoutExtentionOrIncrement +"(" + Integer.toString(c) + ")" + extension;
newFile = new File(path);
}
return newFile;
}
public static String getFileExtension(String filename) {
if (filename == null) { return null; }
int lastUnixPos = filename.lastIndexOf('/');
int lastWindowsPos = filename.lastIndexOf('\\');
int indexOfLastSeparator = Math.max(lastUnixPos, lastWindowsPos);
int extensionPos = filename.lastIndexOf('.');
int lastSeparator = indexOfLastSeparator;
int indexOfExtension = lastSeparator > extensionPos ? -1 : extensionPos;
int index = indexOfExtension;
if (index == -1) {
return null;
} else {
return filename.substring(index + 1).toLowerCase();
}
}
Using one regex pattern:
final static Pattern PATTERN = Pattern.compile("(.*?)(?:\\((\\d+)\\))?(\\.[^.]*)?");
String getNewName(String filename) {
if (fileExists(filename)) {
Matcher m = PATTERN.matcher(filename);
if (m.matches()) {
String prefix = m.group(1);
String last = m.group(2);
String suffix = m.group(3);
if (suffix == null) suffix = "";
int count = last != null ? Integer.parseInt(last) : 0;
do {
count++;
filename = prefix + "(" + count + ")" + suffix;
} while (fileExists(filename));
}
}
return filename;
}
The regex pattern explanation:
(.*?) a non greedy "match everything" starting at the beginning
(?:\\((\\d+)\\))? a number in parenthesis (optional)
(?:____________) - is a non capturing group
___\\(______\\)_ - matches ( and )
______(\\d+)____ - matches and captures the one or more digits
(\\.[^.]+)? a dot followed by anything but a dot (optional)
Here's one way of doing it:
String fileName;
File file = new File(fileName);
if(file.exists()) {
int dot = fileName.lastIndexOf('.'), open = fileName.lastIndexOf('('), incr;
boolean validNum = false;
if(fileName.charAt(dot-1) == ')' && open != -1){
String n = fileName.substring(open+1, dot-1);
try {
incr = Integer.parseInt(n);
validNum = true;
} catch(NumberFormatException e) {
validNum = false;
}
}
if(validNum) {
String pre = fileName.substring(0, open+1), post = fileName.substring(0, dot-1);
while(new File(pre + ++incr + post).exists());
fileName = pre + incr + post;
} else {
fileName = fileName.substring(0, dot) + "(1)" + fileName.substring(dot);
}
}
I assume a couple of things:
1) A method called fileExists(String fileName) is available. It returns true if a file with the specified name is already present in the file system.
2) There is a constant called FILE_NAME which in your example case is equal to "text".
if (!fileExists(FILE_NAME)) {
//create file with FILE_NAME.txt as name
}
int availableIndex = 1;
while (true) {
if (!fileExists(currentName)) {
//create file with FILE_NAME(availableIndex).txt
break;
}
availableIndex++;
}
I am not very sure about Android but since its a Java program, you may be able to create File object of the directory in which you want to write.
Once you have this you can see the list of file names already present inside it and other related information. Then you can decide the file name as per your above logic.
File dir = new File("<dir-path>");
if(dir.isDirectory()){
String[] files = dir.list();
for(String fileName : files){
<logic for finding filename>
}
}
If all filenames have an extenstion you could do something like this (just an example you will have to change it to work in your case):
public static void main(String[] args)
{
String test = "test(1)foo.txt";
String test1 = "test(1)foo(1).txt";
Pattern pattern = Pattern.compile("((?<=\\()\\d+(?=\\)\\.))");
Matcher matcher = pattern.matcher(test);
String fileOutput = "";
String temp = null;
int newInt = -1;
while(matcher.find())
{
temp = matcher.group(0);
}
if(temp != null)
{
newInt = Integer.parseInt(temp);
newInt++;
fileOutput = test.replaceAll("\\(\\d+\\)(?=\\.(?!.*\\.))", "(" + newInt + ")");
}
else
{
fileOutput = test;
}
System.out.println(fileOutput);
matcher = pattern.matcher(test1);
fileOutput = "";
temp = null;
while(matcher.find())
{
temp = matcher.group(0);
}
if(temp != null)
{
newInt = Integer.parseInt(temp);
newInt++;
fileOutput = test1.replaceAll("\\(\\d+\\)(?=\\.(?!.*\\.))", "(" + newInt + ")");
}
else
{
fileOutput = test1;
}
System.out.println(fileOutput);
}
Output:
test(1)foo.txt
test(1)foo(2).txt
This uses regex to look for a number in the () right before the last ..
Update
replaceAll() changed to handle case where there is a . after the first (1) in test(1).foo(1).txt.
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);
}
My application tracks the distance and shows the result in km on the screen. I save the geopoints in an ArrayList. I’d like to export the geopoints as a GPX track file to my sdcard.
I tried https://sourceforge.net/projects/gpxparser/. But after the command GPXParser p = new GPXParser(); my app crashes. (I couldn’t find out how to “instantiate the GPXParser class”, maybe that’s why it didn’t work).
Importing GPX files works flawless with this approach http://android-coding.blogspot.de/2013/01/get-latitude-and-longitude-from-gpx-file.html
Could anyone point me in a direction or give me a hint. I’ve search a lot, but couldn’t find anything I could get to work.
Update!
I've found a solution. Maybe not perfect, but it works.
To save my track, I use the following from my Map-Activity.
Maybe some has a better solution :-).
public void saveRoute(String filename) {
Toast.makeText(this, mTrace.size() + "", Toast.LENGTH_SHORT).show();
String fileName = filename;
// routeFile = new File(getFilesDir(), FILENAME);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/kml");
myDir.mkdirs();
File file = new File(myDir, fileName + ".gpx");
savegpx gpxFile = new savegpx();
try {
file.createNewFile();
gpxFile.writePath(file, fileName, mTrace);
// Log.i(TAG, "Route Saved " + file.getName());
} catch (Exception e) {
Log.e("WritingFile", "Not completed writing" + file.getName());
}
}
Separate class
public class savegpx {
private static final String TAG = savegpx.class.getName();
public savegpx() {
}
/**
* Writes locations to gpx file format
*
* #param file file for the gpx
* #param n name for the file
* #param points List of locations to be written to gpx format
*/
public static void writePath(File file, String n, ArrayList<GeoPoint> points) {
final Context applicationContext= MainActivity.getContextOfApplication();
String header = "<gpx creator=\"Off-Road Tracker\" version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n";
String metadata = " <metadata>\n" + " <time>1900-01-01T00:00:00Z</time>" + "\n </metadata>";
String name = " <trk>\n <name>" + n + "</name>\n <trkseg>\n";
String segments = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
List<String> stockList = new ArrayList<String>();
for (int i = 0; i < points.size(); i++) {
stockList.add(" <trkpt lat=\"" + (points.get(i)).getLatitude() + "\" lon=\"" + (points.get(i)).getLongitude() + "\">\n <ele>" +(points.get(i).getAltitude()) + "</ele>\n <time>" + df.format(new Date()) + "Z</time>\n </trkpt>\n");
}
segments +=stockList;
segments = segments.replace(",","");
segments = segments.replace("[","");
segments = segments.replace("]","");
Toast.makeText(applicationContext, segments, Toast.LENGTH_LONG).show();
String footer = " </trkseg>\n </trk>\n</gpx>";
try {
FileWriter writer = new FileWriter(file);
writer.append(header);
writer.append(metadata);
writer.append(name);
writer.append(segments);
writer.append(footer);
writer.flush();
writer.close();
Log.i(TAG, "Saved " + points.size() + " points.");
} catch (IOException e) {
//Toast.makeText(mapsActivity.getApplicationContext(),"File not found",Toast.LENGTH_SHORT);
Log.e(TAG, "Error Writting Path", e);
}
}
}