Changing a string dynamically for file usage - java

I am trying to figure out how to make a string that I can use to create a file in my java program. I have tried many different ways of doing this, but nothing seems to do what I want.
Here is an example of what I am trying to do:
String fileExt = ".jpg"
for (int i = 0; i < someNumber; i ++){
fileExt = i + fileExt;
}
I want to output something like:
1.jpg
2.jpg
3.jpg
4.jpg
... and so on.
My intention is to use the changed string at every iteration in order to create a new file with it like so : File image = new File (fileExt;

List<File> files = new ArrayList<File>();
String fileExt = ".jpg"
for (int i = 0; i < someNumber; i ++){
File newfile = new File(i + fileExt);
files.add(newfile)
}
A few things here. filext should be absolute path, or the files will be created in your current directory. Keep file references in List for future use.

No matter what you do, the value of fileExt is going to be the last iteration of the loop. Maybe an array will do the trick?
String[] fileExt = new String[20];
for (int i = 0; i < fileExt.length; i++) {
fileExt[i] = i + ".jpg";
}
// view results
for (int i = 0; i < fileExt.length; i++) {
System.out.println(fileExt[i]);
}
// example
File image = new File(fileExt[0]);

Related

How to iterate through multiple folders and compare pdfs stored in it using Java

I am trying to compare PDF files stored in different folders one by one below is the code I wrote in it when using that when it compares the second PDF file(file 22)of folder (data) its taking the first PDF from the other folder to compare can any one help
String object ="D:\\test.pdf";
String data ="D:\\test2.pdf";
Log.info("PDF Documents has been Verified");
// boolean isEquals = false;
try{
String result =Constants.Path_Result+DriverScript.s;
File[] file10 = new File(object).listFiles(File::isFile);
for (File file1: file10) {
String fileExtension = file1.getName().split("\\.")[file1.getName().split("\\.").length - 1];
if (fileExtension.toLowerCase().equals("pdf")) {
file12 =file1.getAbsolutePath();
System.out.println(file12);
File[] file121 = new File(data).listFiles(File::isFile);
for (File file2: file121) {
String fileExtension1 = file2.getName().split("\\.")[file2.getName().split("\\.").length - 1];
if (fileExtension1.toLowerCase().equals("pdf")) {
String file22 =file2.getAbsolutePath();
new de.redsix.pdfcompare.PdfComparator(file12, file22).compare().writeTo(result+"//"+file2.getName());
}}}}
}catch(Exception e){
System.out.println(e.getMessage());
Log.error("Not able to Close the Browser --- " + e.getMessage());
DriverScript.bResult = false;
}
}```
Hi use the below java code it will work
(What i did was combined two of your for loop that you have written in to one so that both the folders will get iterated at the same time.)
String path1 = "D:\\newfolder\\";
String path2 = "D:\\newfolder1\\";
String result="D:\\result\\";
File folder1 = new File(path1);
File folder2 = new File(path2);
File[] listOfFiles1 = folder1.listFiles();
File[] listOfFiles2 = folder2.listFiles();
ArrayList<String> fileNames1 = new ArrayList<String>();
ArrayList<String> fileNames2 = new ArrayList<String>();
for ( int i = 0,j = 0; i < listOfFiles2.length&& j < listOfFiles1.length; i++,j++)
if (listOfFiles2[i].isFile()&&listOfFiles1[j].isFile())
{ fileNames2.add(listOfFiles2[i].getName().split("\\.")[listOfFiles2[i].getName().split("\\.").length - 1]);
fileNames1.add(listOfFiles1[j].getName().split("\\.")[listOfFiles1[j].getName().split("\\.").length - 1]);
String str = fileNames1.toString();
str.toLowerCase().equals("pdf");
String file01 =listOfFiles1[j].getName();
file12 =listOfFiles1[j].getAbsolutePath();
String str1 = fileNames2.toString();
str1.toLowerCase().equals("pdf");
file0 =listOfFiles2[i].getName();
file22 =listOfFiles2[i].getAbsolutePath();
new de.redsix.pdfcompare.PdfComparator(file12,file22).compare().writeTo(result+"//"+file0);
}

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);
}

How to rename file 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"));
}
}

Java autogenerate directories if exists

I'm trying to check if a directory exists, if that happens I want to give it another number, for example, if "folderX" exists I want to create a new one called "FolderX1", at the moment I'm just able to do this once since I have it on an if/else statement like this:
File fa = new File(folder);
if(!fa.exists()){
this.folder = folder;
}else{
this.folder = folder+=1;
}
I want do this recursively, If the program detects that "folderX" exists it should jump and check the others (folderX,FolderX1,FolderX2, etc) until it finds one that can be created but i don't know how to do it.
Basically, you need some kind of loop that can determine if the incrementing folder still exists...
File makeMe = new File(folder);
int index = 0;
String master = folder;
while (makeMe.exists()) {
folder = master + (++index);
makeMe = new File(folder);
}
If you're worried about creating an infinite loop, you could place a maximum range...
int maxRange = 100;
File makeMe = new File(folder);
int index = 0;
String master = folder;
while (makeMe.exists() && index < maxRange) {
makeMe = new File(master + (++index));
}
if (index > maxRange) { // || makeMe.exists()
throw new IOException("Could not find free directory");
} else {
// All happy unicorns...
}
String folderPrefix = "folder";
int folderSuffix = 0;
File fa = new File(folderPrefix + folderSuffix);
while (fa.exists()) {
fa = new File(folderPrefix + folderSuffix++);
}

Error renaming a File in a for loop

I have this code in Java. The randomName() function returns a string with (unsurprisingly) a random string.
File handle = new File(file);
String parent = handle.getParent();
String lastName = "";
for (int i = 0; i < 14; i++)
{
lastName = parent + File.separator + randomName();
handle.renameTo(new File(lastName));
}
return lastName;
I have the appropriate permissions, and when I log to logcat the randomName() function does all the strings, but upon the end of the loop handle appears to have a file name of the value of the first randomName() call.
The reason this didn't work as expected is because once the file was renamed the first time, handle no longer referred to the file. That is why the subsequent rename operations failed. File represents a path name, not an actual object on disk.
This is my solution:
File handle = null;
String parent = "";
String lastName = "";
for (int i = 0; i < 14; i++)
{
if (i == 0)
{
handle = new File(file);
parent = handle.getParent();
}
else
{
lastName = parent + File.separator + randomName();
handle.renameTo(new File(lastName));
handle = new File(lastName);
}
}

Categories

Resources