Rename the file while preserving file extension in java - 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

Related

Pick a particular file from directory using java

I need some help in picking the exact file from directory on Windows using Java. Below is the code which I have written for this. But when I pass my input as "XYZ" file it always picks the "ABC" file only.
My input to pick the file was 'XYZ', but output always returns 'ABC' file
directoryPath = new File(System.getProperty("user.dir") + "\\TestFilesDirectory\\");
String contents[] = directoryPath.list();
System.out.println("List of files and directories in the specified directory : " + directoryPath);
for (int i = 0; i < contents.length; i++) {
// System.out.println(contents[i]);
ArrayList<String> fileNameList = new ArrayList<String>();
String[] fileNameSplit = contents[i].split("_");
for (int k = 0; k < fileNameSplit.length; k++) {
// System.out.println(fileNameSplit[k].toUpperCase());
fileNameList.add(fileNameSplit[k].toUpperCase());
}
if (fileNameList.contains("ABC") {
System.out.println("Pick ABC file from directory ");
source = new File(directoryPath + "\\" + contents[i] + "");
}
System.out.println("Base File: " + source);
else if (fileNameList.contains("DEF") {
System.out.println("Pick DEF file from directory ");
source = new File(directoryPath + "\\" + contents[i] + "");
}
else if (fileNameList.contains("XYZ") {
System.out.println("Pick XYZ file from directory ");
source = new File(directoryPath + "\\" + contents[i] + "");
}
Below are my files in Test directory:
I think that your code can be improved. As far as I can tell you need to retrieve the path of a given file matching either the first or second part of its filename. So for example:
DEF_GHI.txt
can be matched by either inputting def or ghi into your search method. The easiest and most concise way to do so would be:
public Optional<File> findByName(String name, String directoryPath) {
try (var fileStream = Files.list(Path.of(directoryPath))) {
return fileStream
.filter(path -> Arrays.stream(path.getFileName().toString().split("_"))
.map(part -> part.replaceAll("\\.[^.]*$", ""))
.anyMatch(part -> part.equalsIgnoreCase(name)))
.findAny()
.map(Path::toFile);
} catch (IOException e) {
System.err.println("Unable to open directory stream for path:: " + directoryPath);
e.printStackTrace();
}
return Optional.empty();
}
What this does is the following:
Accepts a filename and a path representing a directory to search at
Creates a stream of paths representing the files under the given directory
Gets the filename for each given path and performs the following:
Splits the string using _ in order to retrieve both parts (if present)
Replaces everything after the . character (including it) in order to get rid of the file extension.
Attempts to match each part against the provided name parameter
Map the found path value to a File (if present)
Lastly returns either the optionally wrapped File or an empty Optional.
I hope this is what you are looking for.

how to include path in string array with the file in android

am working with Bitmap.decodeFile(pathname,bOptions), I wanted to include the file detected by the phone in the mean time am using this one
String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Temp Images";
this is only single one of string and I can't include in my array, I want to do is to pass the parameter to my method which is accepting String[] files which includes the pathFile + filename
ex: sd0/pictures/temp file/img1.jpeg
Supossing you have a variable where the file name is stored:
String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Temp Images" + File.separator + fileName;
public String getPath(String folderName, String fileName){
return Environment.getExternalStorageDirectory().toString() + folderName + File.separator + fileName;
}
using the method:
String path = getPath("/Pictures/Temp Images", "img1.jpeg");
or
String path = getPath("/Pictures/Temp Images", fileName);

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.

Create a File in a folder

In Java, I have a File object representing a folder:
String folderName = "/home/vektor/folder";
File folder = new File(folderName);
Now I want to create another File representing a file in this folder. I want to avoid doing a string concatenation like this:
String fileName = "test.txt";
File file = new File(folderName + "/" + fileName);
Because if I go deeper in creating this structure, I will come up with something like this:
File deepFile = new File(folderName + "/" + anotherFolderName + ... + "/" + fileName);
I would instead like to do something like
File betterFile = folder.createUnder(fileName);
Or even:
File otherFile = SomeFileUtils.createFileInFolder(folder, fileName);
Do you know of such solution?
Note: It's quite OK to use "/" because Java will translate it to "\" for Windows, but it is not clean - I should use something like "file.separator" from System.getProperties().
Look at the Javadoc for File and you will see that the constructor takes a File object as parent.
Use the following form:
File deepFile = new File(folder, fileName);
I would use
String folderName =
String fileName =
File under = new File(folderName, fileName);
or
File folderFile =
String fileName =
File under = new File(folderFile, fileName);
simple as that ;)

Generate filename for a copied file

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

Categories

Resources