How to arrange and rename files according to number? - java

I want to arrange files first and rename them according to their order that is specified by a number in the file name.
For example:
I have a folder that contains a bunch of different files. The file names are indicated by a number at the end of it. Let's say we have the following files in that folder:
file_1.xml // Remains unchanged
file_2.xml // Remains unchanged
file_4.xml // Should be renamed to "file_3.xml"
file_9.xml // Should be renamed to "file_4.xml"
file_12.xml // Should be renamed to "file_5.xml"
How do I do that? I want to create a reliable clean method that renames files in order.
So far:
private void updateFilesName() {
for (int i = 1; i <= filesAmount; i++) {
File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml");
File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml");
if (!file1.exists() && file2.exists()) {
file2.renameTo(file1);
}
}
}
But that only works if the difference between 2 file positions was 1. (like between file_2 and file_4) This method won't work for file_9 and file_12.

private void updateFilesName() {
int j;
for (int i = 1; i <= filesAmount; i++) {
File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml");
if (!file1.exists()) {
j = i+1;
while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) {
j++;
}
(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1);
}
}
}

// Iterate all files under the directory and check the file name
File folder = new File("urdirectory");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
if (!listOfFiles[i].getName().equals("file_" + (i+1) + ".xml")) {
File tempFile1 = listOfFiles[i];
File tempFile2 = new File("urdirectory" + "/file_" + String.valueOf(i + 1) + ".xml");
tempFile.renameTo(tempFile2);
}
}

Related

Always the last element's informations are shown in the List (Java)

I have some Lists consist of some Apk files' informations:
static ContentAndDAO contentAndDao = new ContentAndDAO();
public static void main(String[] args)
{
int manifestNum;
long contentId = 111111;
long devFileId = 222222;
List<DevFile> fileList;
List<DevSupport> supports = null;
List<ContentDev> contentList = new ArrayList<ContentDev>();
ContentDevDAO contentDevDao = new ContentDevDAO();
DevFileDAO devFileDao = new DevFileDAO();
ManifestMethods manifestMethods = new ManifestMethods();
DevFile apkFile = null;
try
{
manifestNum = 1;
File dir = new File("C:\\Users\\lenovo 01\\Desktop\\basari\\buulkcontent\\klasorlenen");
String[] extensions = new String[] {"apk"};
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
Collections.sort(files);
for(File file : files)
{
apkFile = new DevFile();
fileList = new ArrayList<DevFile>();
if(file.getName().contains(".apk"))
{
FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath()));
String apkMd5 = DigestUtils.md5Hex(fis);
fis.close();
System.out.println(file);
System.out.println(file.length());
System.out.println(apkMd5.toUpperCase());
System.out.println(contentId);
apkFile.setByteSize(file.length());
apkFile.setUrl("/file/getContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setThumbnailUrl("/file/getContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setDeleteUrl("/file/deleteContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setFileHash(apkMd5.toUpperCase());
apkFile.setFilePath("content/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + ".apk");
apkFile.setFileName(manifestMethods.getApplicationName(manifestNum).replaceAll(" ", "-") + ".apk");
apkFile.setName(manifestMethods.getApplicationName(manifestNum).replaceAll(" ", "-"));
apkFile.setPackageVersion(manifestMethods.getVersionName(manifestNum));
apkFile.setPackageName(manifestMethods.getPackageName(manifestNum));
apkFile.setPackageVersionCode(manifestMethods.getVersionCode(manifestNum));
apkFile.setSdkVersion(manifestMethods.getSdkVersion(manifestNum));
contentId++;
devFileId++;
manifestNum++;
}
}
for(int y = 1; y <= 53; y++)
{
manifestNum = 1;
fileList = new ArrayList<DevFile>();
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
content.setDevFiles(fileList);
contentList.add(content);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
When I print the information one by one to the console, its showing just as I want. But in the List, its always showing only the last added apk file's package name, byte size, hash number etc. Of course I don't want that. What is wrong?
Note: Please don't mind the lack of legibility and modularity of code. I'm new to the object oriented structure.
You are creating a new list in each iteration of your loop :
for(int y = 1; y <= 53; y++)
{
fileList = new ArrayList<DevFile>();
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
...
This means only the last file will be in that list at the end.
Change it to :
fileList = new ArrayList<DevFile>();
for(int y = 1; y <= 53; y++)
{
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
...
In addition, I see that you create instances of DevFile in another loop, but never do anything with them. Shouldn't they be added to the List?

Comparing two byte arrays in java

I am trying to develop a program that searches for duplicate files using MD5 hash, it will compare two hash files for duplicate.
I am having difficulties comparing the two files, after hashing the files with MD5 hash code, I keep getting the error "Java.IO.FileNotFoundException.". Here is my code, I do not know what I am doing wrong.
////////////////////// It is a GUI Program ////////////////////////
DefaultListModel m = new DefaultListModel(); // List Model for displaying the hash codes
int rval = chooser.showOpenDialog(null); //JFileChooser for selecting files tobehashed
if(rval == JFileChooser.APPROVE_OPTION){
File f = chooser.getCurrentDirectory();
String fs = f + "";
if(!f.isDirectory()){
JOptionPane.showMessageDialog(null, "Supplied Directory does not exist");
}
//display files on the TesxtField component
File[] filenames = f.listFiles();
String fn = Arrays.toString(filenames);
String type = f.isFile() ? "File" : "Directory : ";
long len = f.length();
String all = type +" "+" " + " Length: " + len;
dis.setText(all + "\n");
dis.setText(fn + "\n" + "\n" );
//Loops through the file and check sum of the list files
for(File file : f.listFiles()){
String hash;
try {
hash = MD5.asHex(MD5.getHash(file));
////////// Here is where my problems starts, Please help //////////
for(int i = 0; i < hash.length(); i++ )
for(int j = i + 1; j < hash.length(); j++){
File[] f1 = new File[i];
File[] f2 = new File[j];
boolean check = MD5.hashesEqual(MD5.getHash(new File(Arrays.toString(f1))),MD5.getHash(new File(Arrays.toString(f2)))); //compares the byte of files
System.out.println(check);
m.addElement(hash);
task.setModel(m);
}
}catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
For reading files in Java you need an InputStream object.
Look at this Question Getting a File's MD5 Checksum in Java which seems to help you with your problem

Java Path Files.copy rename if exists

just a simple question, with a hard (for me) to find answer :D. Here is my code (im going to try to translate the spanish part):
File carpetanueva = new File("C:"+File.separator+"sistema" + File.separator +
fechasal+File.separator+doc);
carpetanueva.mkdirs();
carpetanueva.setWritable(true);
rutadestino = ("c:"+File.separator+"sistema" +
File.separator + fechasal+File.separator +
doc+File.separator+"imagen.jpg");
//realizo la copia de la imagen desde el jfilechooser a su destino:
Path desde = Paths.get(rutaorigen);
Path hacia = Paths.get(rutadestino);
try {
Files.copy(desde, hacia);
JOptionPane.showMessageDialog(null,
"Se adjunto la planilla de ambulancia correctamente");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "error: "+e.getLocalizedMessage());
}
I get "rutaorigen" (frompath) from a JFileChooser. And I create "rutadestino" (topath) by using some variables so this way i can give an order. The problem is.. .if directories and the file "imagen.jpg" already exists, it gives an error.. (exception).. How can i make to check if image already exists, and if it does, rename the new image to , for example, imagen2? I cant figure out code, because im a newbie, I did a research and couldnt find something like this! Thanks in advance :)
OK, here is a quick solution if src is a Path to the file you want to copy, dst a Path to the file you want to write, and newName a Path to the file you want to rename to:
if (Files.exists(dst))
Files.move(dst, newName);
Files.copy(src, dst);
Note that you can use the methods in Path to facilitate your path building: .resolve(), .resolveSibling(), .relativize().
Edit: here is a function which will return a suitable name given a directory (dir), a base filename baseName and an "extension" (without the dot) extension:
private static Path findFileName(final Path dir, final String baseName,
final String extension)
{
Path ret = Paths.get(dir, String.format("%s.%s", baseName, extension));
if (!Files.exists(ret))
return ret;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
ret = Paths.get(dir, String.format("%s%d.%s", baseName, i, extension));
if (!Files.exists(ret))
return ret;
}
throw new IllegalStateException("What the...");
}
I think this link will help How do I check if a file exists?
So for your case, probably do something like:
File toFile = new File(rutadestino);
if (toFile.exists()) {
// rename file
toFile.renameTo(new File("newFilePath/newName.jpg"));
} else {
// do something if file does NOT exist
}
Hope that helps! For more info, also check the Java Docs for File
sory late. but my code can help to litle bit.
public void copyFile(File source, File dest) throws IOException,
FileAlreadyExistsException {
File[] children = source.listFiles();
if (children != null) {
for (File child : children) {
if (child.isFile() && !child.isHidden()) {
String lastEks = child.getName().toString();
StringBuilder b = new StringBuilder(lastEks);
File temp = new File(dest.toString() + "\\"
+ child.getName().toString());
if (child.getName().contains(".")) {
if (temp.exists()) {
temp = new File(dest.toString()
+ "\\"
+ b.replace(lastEks.lastIndexOf("."),
lastEks.lastIndexOf("."), " (1)")
.toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName().toString());
}
b = new StringBuilder(temp.toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName());
}
if (temp.exists()) {
for (int x = 1; temp.exists(); x++) {
if (child.getName().contains(".")) {
temp = new File(b.replace(
temp.toString().lastIndexOf(" "),
temp.toString().lastIndexOf("."),
" (" + x + ")").toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName() + " (" + x + ")");
}
}
Files.copy(child.toPath(), temp.toPath());
} else {
Files.copy(child.toPath(), temp.toPath());
}
} else if (child.isDirectory()) {
copyFile(child, dest);
}
}
}
}
features :
1. rename if file exist in the destination. example: document.doc if exist document (1).doc if exist document (2).doc if exist ...
2. copy all file from source (only file) to one folder in destination
The code below checks if the file already exists in destination, if it does, it appends #1 to file name just before the extension. If that file name also exists, it keeps appending #2,#3,#4... till the file name doesn't exist in destination. Since () and spaces create problems in Unix environment, I used # instead.
You can extend this and do a SUMCHECK if the file in destination with the identical name also has the same content and act accordingly.
Credit goes to johan indra Permana
String lastEks = file.getName().toString();
StringBuilder b = new StringBuilder(lastEks);
File temp = new File(backupDir.toString() + File.separator + file.getName().toString());
if (file.getName().contains(".")) {
if(temp.exists()) {
temp = new File(backupDir.toString() + File.separator +
b.replace(lastEks.lastIndexOf("."), lastEks.lastIndexOf("."),"#1").toString());
} else {
temp = new File(backupDir.toString() + File.separator + file.getName().toString());
}
b = new StringBuilder(temp.toString());
} else {
temp = new File(backupDir.toString() + File.separator + file.getName());
}
if (temp.exists()) {
for (int x=1; temp.exists(); x++) {
if(file.getName().contains(".")) {
temp = new File (b.replace(
temp.toString().lastIndexOf("#"),
temp.toString().lastIndexOf("."),
"#" + x ).toString());
} else {
temp = new File(backupDir.toString() + File.separator
+ file.getName() + "#" + x );
}
}
Files.copy(file.toPath(), temp.toPath());
} else {
Files.copy(file.toPath(), temp.toPath());
}

Converting working code into a recursive method

Hi guys I needed to create a method to display current directory, files, subdirectories and the files of those subdirectories given a file the user has to choose. I accomplished the task and the fallowing code is printing the appropriated output. It is printing from the f.getParentFile() down, that is what want. Now I want to use recursion instead. I am trying to learn the concept of recursion. I know you need a base case and then your inductive step, but when I try to modify my code into recursive I get an infinite loop when it hits the first subdirectory. Any feedback will be appreciated.
NON-Recursive Working code
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
File[] listFiles = list[i].getAbsoluteFile().listFiles();
for (int j = 0; j < listFiles.length; j++)
{
System.out.println("\t\tSubdirectory files: " + listFiles[j].getName() + "\tsize :" + (listFiles[j].length()/1024) + "KB" );
}
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
Attempting Recursion
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
listFiles(list[i].getAbsoluteFile());
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
It is really really simple :)
public static void main(String[] args) {
filesInFolder("./");
}
public static void filesInFolder(String filename) {
File dir = new File(filename);
for (File child : dir.listFiles()) {
System.out.println(child.getAbsolutePath());
if (child.isDirectory()){
filesInFolder(child.getAbsolutePath());
}
}
}

How to change names of files in String[]

I have such code...
File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
String[] files = fileDir.list();
So, I have an array of files' names...
But I want to GET an array of "path to each file"+fileDir.list()
For example
I have - "/09.jpg"
I want - "/mnt/sdcard/dd/09.jpg"
How can I do it? Thanks
try following code,
String path = "/mnt/sdcard/dd";
File fileDir = new File( path );
if(!fileDir.exists() || !fileDir.isDirectory())
{
return;
}
String[] files = fileDir.list();
for ( int i = 0 ; i < files.length ; i++ )
{
files[i] = path + "/" + files[i];
}
Now the array files contains the updated value with path.
File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
File[] files = fileDir.listFiles();
for(File f: files){
Log.i("", f.getAbsolutePath());
}
What you need is getAbsolutePath(),
File file = new File("/mnt/sdcard/dd");
Files[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
Log.e("Root Path of file:" + i, files[i].getAbsolutePath());
}

Categories