Generate filename for a copied file - java

I am looking to get similar behaviour to what you get in Windows when you copy and paste a file in the same directory.
For e.g, if you've copy/paste a file called foo.txt, it will create foo Copy.txt and if you paste it once more, it creates foo Copy(2).txt and if you copy/paste foo Copy.txt, foo Copy Copy.txt is created.
Is there a Java utility function that does this? I've looked at File.createTempFile but the filename it generates is too long and contains a UID-like substring.

By using the FileChooser in combination with the "showSaveDialog"-method you will get the result you want, because java is then using the OS behaviour for existing files.

Sometimes, you just have to do the work first, it will give you an appreciation for the API. Then you can write your own utility methods
File original = new File("build.xml");
String path = original.getAbsoluteFile().getParent();
String name = original.getName();
String ext = name.substring(name.indexOf("."));
name = name.substring(0, name.indexOf("."));
name = path + File.separator + name;
int index = 1;
File copy = new File(name + " (" + index + ")" + ext);
while (copy.exists()) {
index++;
copy = new File(name + " (" + index + ")" + ext);
}
System.out.println(copy);

Related

Alternative ways to rename a flat file in Java

So im writing a program that reads a txt file that the user provides the name of from a specific folder
I want to rename the .txt after the user has opened it. However, nothing happens
temp = userInput;
currentFileDir = "D:\\Document\\" + username + "\\" + temp1 ;
File directory = new File(currentFileDir + ".txt");
Scanner readingFile = new Scanner(directory);
while (readingFile.hasNextLine())
{
txtdata = txtdata + readingFile.nextLine() + " ";
}
File newName = new File(currentFileDir + "--OPENED.txt");
directory.renameTo(newName);
System.out.println(txtdata);
}
Is there something wrong with the code I provided?
I've tried using it in a standalone program and it works fine, so I think that the rest of the code of my program must interfere with the rename process.
Are there any alternatives to "renameTo"?

How can I solve the error of the "no such a directory or file"?

I have this simple code, but when I run, I get an error of not such a directory or file! how can I solved I tried many ways none of them works!! can anyone help?
public static void main (String [] args) {
String songA = ("res/raw/canon_d_major.wav");
String songB = ("res/raw/canon_d_major.wav");
Wave waveA = new Wave(songA);
Wave waveB = new Wave(songB);
String recordedClip = ("res/raw/cock_a.1.wav");
Wave waveRec = new Wave(recordedClip);
FingerprintSimilarity similarity1, similarity2;
similarity1= waveA.getFingerprintSimilarity(waveRec);
System.out.println("clip is found at " +
similarity.getsetMostSimilarTimePosition() + "s in " + songA +
" with similarity " + similarity.getSimilarity());
similarity2 = waveB.getFingerprintSimilarity(waveRec);
System.out.println("clip is found at " +
similarity.getsetMostSimilarTimePosition() + "s in " + songB +
" with similarity " + similarity.getSimilarity());
}
File fileName = new File('path/to/file'); does not create file on your hdd. Its only new File object in java that points to the dir you set in constructor. With that said if cock_a.wav doesnt exist while code is executing it wont be physically created.
Use this -> Java's createNewFile() - will it also create directories?
Also it might be helpful if you post your directory structure here.

Rename file in JFileChooser if file exists and user inputs extension

The code works as it has to until user inputs a filename with extension (.txt) and it already exists. So if the file "test.txt" exists and the user decides to name the new file as "test", it will be named as "test(1).txt", but if the user adds extension like "test.txt", the file will be named as "test.txt" and the next file user names "test.txt" will be saved as "test.txt(1).txt".
Is it possible to get the name of file from JFileChooser, remove it's extension if user input it and use it as name of the new file after adding number in the middle of original file name and it's extension? I can get name without extension as String type, but I need it as File type.
File ft = fc.getSelectedFile();
String ext = ".txt";
File tmp = new File(ft.getPath());
if (!fc.getSelectedFile().getAbsolutePath().endsWith(ext)){
ft = new File (ft + ext);
}
File test = new File(ft.getPath());
File temp = new File(ft.getPath());
File temp1 = new File(ft.getPath());
int count = 1;
while (temp.exists()) {
if(tmp.getAbsolutePath().endsWith(ext)){
}
File ft1 = new File (tmp + "(" + count + ")");
ft = new File (tmp + "(" + count + ")" + ext);
count++;
temp = new File(ft.getPath());
temp1 = new File(ft1.getPath());
}
if (!temp1.getAbsolutePath().endsWith(ext)){
ft = new File (temp1 + ext);
}
int cnt = count - 1;
if (!test.equals(temp)){
JOptionPane.showMessageDialog(null, "File already exists. So it's saved with (" + cnt + ") at the end.");
}
OK so I've tried to make this work without changing your code too much. Try this:
String filePath = fc.getSelectedFile().getAbsolutePath();
final String ext = ".txt";
String filePathWithoutExt;
if (filePath.endsWith(ext)) {
filePathWithoutExt = filePath.substring(0, filePath.length() - ext.length());
} else {
filePathWithoutExt = filePath;
}
File test = new File(filePathWithoutExt + ext);
File temp = new File(filePathWithoutExt + ext);
int count = 0;
while (temp.exists()) {
count++;
temp = new File(filePathWithoutExt + "(" + count + ")" + ext);
}
if (!test.equals(temp)) {
JOptionPane.showMessageDialog(null,
"File already exists. So it's saved with (" + count + ") at the end.");
}
EDIT:
By the recommendation of Marco N. it could be better to determine whether or not an extension exists by finding the last position of the . since this would also work with extensions other than ".txt". This value would then be used to split the string. The replacement code would look like this:
final int lastPeriodPos = filePath.lastIndexOf(".");
if (lastPeriodPos >= 0) {
filePathWithoutExt = filePath.substring(0, lastPeriodPos);
} else {
filePathWithoutExt = filePath;
However this would also have some issues if the user entered a file name that contained the . anywhere other than just before the file extension.
Hmm, I think this entry might be useful as well:
Remove filename extension in Java
I currently lack the time to properly test it (or better test it at all) but shouldn't it work this way:
public static String removeExtention(File f) {
String name = f.getName();
// Now we know it's a file - don't need to do any special hidden
// checking or contains() checking because of:
final int lastPeriodPos = name.lastIndexOf('.');
if (lastPeriodPos <= 0)
{
// No period after first character - return name as it was passed in
return f;
}
else
{
// Remove the last period and everything after it
File renamed = new File(f.getParent(), name.substring(0, lastPeriodPos));
return renamed;
}
}
I briefly tried to adjust the code from the posting mentioned above and it may very well contain some errors or flaws. (If you find some, do not hesitate to comment on them. Some of them might be due to my current lack of time, but I am always willing to learn and improve.) However I hope this may help you to find a proper solution to your problem.

Rename the file while preserving file extension in java

How to rename a file by preserving file extension?
In my case I want to rename a file while uploading it. I am using Apache commons fileupload library.
Below is my code snippet.
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
//renaming uploaded file with unique value.
String id = UUID.randomUUID().toString();
File newName = new File(path + "/" + id);
if(uploadedFile.renameTo(newName)) {
} else {
System.out.println("Error");
}
The above code is changing the file extension too. How can I preserve it?
Is there any good way with apache commons file upload library?
Try to split and take only the extension's split:
String[] fileNameSplits = fileName.split("\\.");
// extension is assumed to be the last part
int extensionIndex = fileNameSplits.length - 1;
// add extension to id
File newName = new File(path + "/" + id + "." + fileNameSplits[extensionIndex]);
An example:
public static void main(String[] args){
String fileName = "filename.extension";
System.out.println("Old: " + fileName);
String id = "thisIsAnID";
String[] fileNameSplits = fileName.split("\\.");
// extension is assumed to be the last part
int extensionIndex = fileNameSplits.length - 1;
// add extension to id
System.out.println("New: " + id + "." + fileNameSplits[extensionIndex]);
}
BONUS - CLICK ME

Code cannot find my file

I have written a short program that will find a file I have made and print some of its details. It executes all right, but it cannot detect the file size or if it is hidden or not. E.G.
file path: C:\temp\filetext.txt last modified: 0 file size: 0 Is file hidden?false
The file does exist in the temp folder on C. I'm not really sure what the problem is
public void Q1()
{
String fileName = "filetext.txt";
getFileDetails(fileName);
}
public void getFileDetails(String fileName)
{
String dirName = "C:/temp/";
File productsFile = new File(dirName + fileName);
long size = productsFile.length();
System.out.println("file path: " + productsFile.getAbsolutePath() + " last modified: " + productsFile.lastModified() + " file size: " + productsFile.length() + " Is file hidden?" + productsFile.isHidden());
}
File does not need a physical file to work with. Therefore your File object can exist even if the physical file it is supposed to represent does not exist/cannot be found. Check the JavaDoc for length() and lastModified(), they both return 0L in case for example the file does not exist. So make sure your File objects is linked to an existing file on your file system by calling file.exists() before calling the other methods.

Categories

Resources