Java create multiple new files - java

I read this question here How to create a file in a directory in java?
I have a method that creates a QR Code. The method is called several times, depends on user input.
This is a code snippet:
String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);
The problem: If the user types "2" then this method will be triggered twice.
As a result, the first qrCODE.png file will be replaced with the second qrCODE.png, so the first one is lost.
How can I generate more than one qr code with different names, like qrCODE.png and qrCODE(2).png
My idea:
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Any tips?
EDIT: I solved it by using a for loop and incrementing the number in the filename in every loop step.

You can create more files eg. like follows
int totalCount = 0; //userinput
String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";
for(int counter = 0; counter < totalCount; counter++){
int size = 250;
//tbd
File myFile = new File(filePath+fileName+counter+"."+fileType);
/*
will result into files qrCODE0.png, qrCODE1.png, etc..
created at the given location
*/
}
Btw to add check if file exists is also good point.
{...}
if(!myFile.exists()){
//file creation
myFile.createNewFile()
}else{
//file already exists
}
{...}

Your idea of solving the problem is a good one. My advice is to break up the filePath variable into a few variables in order to manipulate the file name easier. You can then introduce a fileCounter variable that will store the number of files created and use that variable to manipulate the name of the file.
int fileCounter = 1;
String basePath = "/Users/Test/";
String fileName = "qrCODE";
String fileType = ".png";
String filePath = basePath + fileName + fileType;
File myFile = new File(filePath);
You can then check if the file exists and if it does you just give a new value to the filePath variable and then create the new file
if(myFile.exists()){
filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
myFile = new File(filePath);
}
createFile(myFile);
And you're done!

You can check /Users/Test direcroty before create file.
String dir = "/Users/Test";
String pngFileName = "qrCode";
long count = Files.list(Paths.get(dir)) // get all files from dir
.filter(path -> path.getFileName().toString().startsWith(pngFileName)) // check how many starts with "qrCode"
.count();
pngFileName = pngFileName + "(" + count + ")";

Related

How do I make a new file everytime so nothing gets overwritten?

I have this code here that saves bitmaps of images as a GIF file called test, but everytime the user saves it as test.gif so its constantly overwriting.
What are some ways to avoid overweriting and generate a new filename everytime programmatically?
if(imagesPathList !=null){
if(imagesPathList.size()>1) {
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "test.gif");
try{
FileOutputStream f = new FileOutputStream(file);
f.write(generateGIF(list));
} catch(Exception e) {
e.printStackTrace();
}
A quick and dirty solution is to put the system time in the filename:
File file = new File(dir, "test_" + System.currentTimeMillis() +".gif");
As long as that method isn't executed at the exact same millisecond, you won't have duplicates.
You can use java.io.File.createTempFile("test", ".gif", dir)
This creates unique filename but they might get significantly long after some time.
Alternatively you can create a method that creates unique filesnames yourself:
private File createNewDestFile(File path, String prefix, String suffix) {
File ret = new File(path, prefix + suffix);
int counter = 0;
while (ret.exists()) {
counter++;
ret = new File(path, prefix + "_" + counter + suffix);
}
return ret;
}
Instead of
File file = new File(dir, "test.gif");
you call
File file = createNewDestFile(dir, "test", ".gif");
This is not thread safe. For that you need a more sophisticated method (e.g. synchronize it and create a FileOutputStream instead of a File which is creating the file already before another call checks of the method checks its existence).

Iterating through array using for loop - keeps failing?

(Hello world level tester here)
I've got a java application to delete a bunch of files post tests to keep everything clean, however the issue is I can't seem to get it to work, this is my first time touching on an array and it's a slightly more complex one than the ones they show in the tutorials, any assistance would be greatly appreciated.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
File filePath = new File(home+fileArray);
System.out.println(filePath);
for (String count: fileArray) {
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(count);
}
You should concat new file path for every element in an array, so need to put work with a file in for body. So in every iteration, you get in variable filePath next element of an array and then you need to concat this variable to base path home + filePath. Now you are looking at needed file, you can create file object and work with it.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
for (String filePath: fileArray) {
File file = new File(home + filePath);
System.out.println(filePath);
if (file.exists()) {
file.delete();
System.out.println("Deleted");
} else {
System.out.println("failed");
Assert.fail();
}
}
Seem like you expect that in variable count you will see a number of iterated files. In this case, it does not work like this. Such form of for acting like this: for (String arrayElement : arrayToWorkWith) - mean that on every iteration in variable arrayElement will be put next element from array arrayToWorkWith. If you need to count number of element during iterations you can introduce separate variable and increment it or use another form of for cycle - for (int i = 0; i < fileArray.length; i++).
try it this way
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
//File filePath = new File(home+fileArray); thats wrong here and will give you a invalid file anyway as you concatenating a string with an object
for (String file: fileArray) {
File filePath = new File(home+file); //here you need to define the file
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(file);
}

How to create a file object for which some part is always changing

I'd like to create a file object as follows
File file = new File("MyFile-abcdfg.txt");
where the string between - and . is random and always changing. The length is also not the same.
I want to check the file.exist(), but the problem is I am not sure what will be the name of the file, as it keeps on changing.
You can find the Possible solution over here.
List of files starting with a particular letter in java
Thanks
You can create a String variable for example like this:
String dynamicPartOfFileName = "abcdfg";
If you want to you can replace the literal "abcdfg" by any other mechanism (such as generating a randomized String).
And use it as part of the filename like this:
File file = new File("MyFile-" + dynamicPartOfFileName + ".txt");
The +-operator will join the Strings together. Afterwards the new File()-constructor will use the joined String.
You can use random numbers to randomly pick values from your possible file names.
Random rand = new Random();
int randomNumber = rand.nextInt(2); // 0-1.
String s1 = "-";
if(randomNumber == 0){
s1 = "_";
}
int nameLength = rand.nextInt(100); //0-99
String characters = "";
String possibleCharacters = "abcdefg";
for(int i = 0; i < nameLength; i++){
characters += possibleCharacters[rand.nextInt(possibleCharacters.length)];
}
String filename = "MyFile" + s1 + characters + ".txt";
File file = new File(filename);
if(file.exists() && !file.isDirectory()) {
// do something
}
As far as I can tell, your problem is not how to create the file name, but rather, how to check if a file with that possible name exists.
If you know the formation rule for the names (suppose "aBeginning" + "aDatePresentation" + "anEnd"), then you can test for possible files, such as
boolean checkFileToday(){
Date today = new Date();
String name = "aBeginning"+today.getDate()+"anEnd";
File file = new File(name);
return file.exists();
}
The following code, generates new file with the unique name.
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class DynamicFile {
public static void main(String[] args) throws IOException {
int i = 4;
do {
//UUID creates random string.
String randomID = UUID.randomUUID().toString();
File file = new File("A:/NewFolder/MyFile-" + randomID.substring(0, 5) + ".txt");
file.createNewFile();
} while (i-- > 0);
}
}
Will create files like:
MyFile-1d2ef.txt

Create multiple copies of a singlle file in java

i have a fileserver and client and want to rename files, if they already exists in downloadfolder. what is the best way to do that? I tried that code but it always create one copy and the next copy overwrites the first one.
File f = new File(FILE_DIR + fileName);
if(f.exists()) {
System.out.print("file already exists");
fileName = "copy_of_" + fileName;
}
In your class you declare :
private static int X = 0;
and then change the code to this:
File f = new File(FILE_DIR + fileName);
if(f.exists()) {
System.out.print("file already exists");
fileName = "copy_of_ " + X + fileName;
x++;
}
so everytime the x will increase by 1, (x++), so they will have different names.

Java don't read in pictures and audio files with relative path

In java i programmed a small program to play audio file and sow pictures:
At first i make a final String with the path and then i made a file object.
At least i save the returned array in my "tracks" variable.
This is my code:
private static final String PATH = "../src/audio/";
private static final File FILE = new File(PATH);
tracks = liesAudioDateien(file);
private AudioClip[] liesAudioDateien (File inputFile) {
File[] dateFileArray;
AudioClip[] tracks;
dateFileArray = inputFile.listFiles();
tracks = new AudioClip[dateFileArray.length];
for (int i = 0; i < tracks.length; i++) {
if (dateFileArray[i].isFile()) {
try {
tracks[i] = Applet.newAudioClip(dateFileArray[i].toURL());
} catch (IOException ex) {
System.err.println("Oops!: -- " + ex.toString());
}
}
}
return tracks;
If I run this code, I get an error:
Exception in thread "main" java.lang.NullPointerException
at source.Sound.liesAudioDateien(Sound.java:32)
Sound.java:32:
This is tracks = new AudioClip[dateFileArray.length]; line.
If i try with an absolute path, it does work!
What i do wrong?
Change "../src/audio/" to "./src/audio/"
Your path is relative, which is resolved to be relative to the current working directory. The current working directory is not what you think it is.
Try to do this before inputFile.listFiles();
System.out.println(inputFile.getAbsolutePath());
And see what Java thinks the absolute path should be.
File.listFiles returns null if the abstract pathname does not denote a directory.
You need to make sure inputFile does denote a directory to ensure dateFileArray is not null.
Try it with File.separator in place of forward/backward slash.
ex:
String soundDir = "." + File.separator + "folderName" + File.separator;
String fileName = "sound.wav";
String filePath = soundDir+ + fileName;

Categories