Put Brackets around filename - java

This is a correction of my previous question Put brackets around filename for Excel formula
My project is based on Apache POI.I'm trying to use a formula on a cell.
My formula is as follows.
sheet7.createRow(0).createCell(0).setCellFormula("+'C:\\Users\\Desktop\\[Test.xlsx]Average_Graph'!A2");
Im using a JFileChooser, which allows users to select the file. Therefore the filepath will be changed every time the program is used.
From the JFileChooser, I'm getting a filepath as follows.
String filepath= "C:\\Users\\Desktop\\Sheet.xlsx"`
In order to work the formula correctly, the filepath should be in following format.
"C:\\Users\\Desktop\\[Sheet.xlsx]"
How Can I Change the string which I'm getting from the JFileCHooser to run the formula correctly?
In previous question, I mistakenly typed C:\Users\Desktop[Sheet.xlsx] instead of C:\Users\Desktop\[Sheet.xlsx]
The answers gave me the output which i've mentioned. But I need the Output as C:\Users\Desktop\[Sheet.xlsx]
Please help.

If you want to solve this by directly altering the file path, you may use String#replaceAll:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.replaceAll("(?<=\\\\)([^\\\\]+)$", "[$1]");
System.out.println(filepath);
C:\Users\Desktop\[Sheet.xlsx]
Demo

File names won't have \backslashes in them, so we can assume that our filename begins after the last backslash and ends at the end of the string.
We can use this:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
String dir = filepath.substring(0, filepath.lastIndexOf("\\"+1));
String filename = filepath.substring(filepath.lastIndexOf("\\"+1));
filepath = dir + "[" + filename + "]";
Or a shorter version:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.substring(0, filepath.lastIndexOf("\\"+1)) +
"[" + filepath.substring(filepath.lastIndexOf("\\"+1)) + "]";

Related

Random String infront of File Name

Im creating an app in android studio that grabs audio files and reads the metadata.
Uri uri = resultIntent.getData();
String[] split = uri.getPath().split("/");
String path = android.os.Environment.getExternalStorageDirectory().toString()
+"/"+ split[split.length-2]
+ "/" + split[split.length-1];
It works fine when I try to grab from my Downloads Folder but when I attempt to grab from my SD Card, my file has a random string appended infront of it.
/storage/emulated/0/document/1D09-2116:song.mp3
What could I do to remove it?
If that random string maintains the same format everytime then you could possibly use regex alongside the replaceAll() function.
String str;
String regex = ".*-\d+:";
str = str.replaceAll(regex, split[split.length-1]);
String path = android.os.Environment.getExternalStorageDirectory().toString()
+"/"+ split[split.length-2]
+ "/" + str;

Ini4j not reading file paths

I have a .ini file that looks like this:
[Filepath]
Inbound=C:\Users\Bilbo\Desktop\Testing
I want to return that exact string (C:\Users\Bilbo\Desktop\Testing) and I have the following code:
public static String ParseIniInbound (File iniFile) throws
InvalidFileFormatException, IOException {
String iniFileName = iniFile.toString();
Ini ini = new Ini(new File(iniFileName));
String InboundPath= ini.get("Filepath", "Inbound");
return InboundPath;
}
However, what is returned is C:UsersBilboDesktopTesting
I tried putting quotes around the filepath in the .ini file to read it as a string but that didn't work. I used double slashes (C:\\Users\\Bilbo\\Desktop\\Testing) which returns (C:\Users\Bilbo\Desktop\Testing) but I want to be able to just copy and paste a filepath and not have to manually put in double slashes. Is there a way to read in a string from an .ini file with ini4j or another way around this? Thanks
Well I couldn't find anything about this, except your post so here is my solution, but if this is the intended way it is really dumb.
ini.put("Default_Values", "dWorkflowStart", "C:\\" + "\\User\\" + "\\kh\\" + "\\Desktop\\"
+ "\\workstuff\\" + "\\samples\\" + "\\test_in");
This puts out [Default_Values]
dWorkflowStart = C:\\Users\\kh\\Desktop\\workstuff\\samples\\test_in

merging two strings to shape a file path

assuming that we have a folder with path:
path="C:\\Users\\me\\Desktop\\here"
also, consider a File[] named readFrom has different files. as an example, consider following path which refering to a file:
C:\\Users\\me\\Desktop\\files\\1\\sample.txt"
my question is, how can i have a string with following value:
String writeHere= "C:\\Users\\me\\Desktop\\here\\files\\1\\sample.txt"
EDIT
I should have mentioned that this path is unknown, we need first to read a file and get its path then write it into another folder, so for the path of writing I need writeHere as input. in conclusion , the answer should contains the way to get the path from the file too.
String s1="C:\\Users\\me\\Desktop\\here";
String s2="C:\\Users\\me\\Desktop\\files\\1\\sample.txt";
String s3=s2.substring(s2.indexOf("\\files"));
System.out.println(s1+s3);
OUTPUT
C:\Users\me\Desktop\here\files\1\sample.txt
To get Absolute Path of file
File f=new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
System.out.println(f.getAbsolutePath());
Split the into arrays and merge the path with split-ted string
String path="C:\\Users\\me\\Desktop\\here";
String [] splt = yourPath.split("\\");
finalPath = path + "\\" + splt[3] + "\\" + splt[4] + "\\" + splt[5];
yourPath is the path refering to a file
Changing the folder's path
File afile =new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
afile.renameTo(new File(finalPath))
If you just need the String and do not need to read the file, use string concatenation with is just str1 + str2. If you need the File object create a base File object on the initial path and then two new File objects from that:
File path = new File("C:\\Users\\me\\Desktop\\here");
String[] files = { "files\\1\\sample.txt", "files\\3\\this.avi" };
for (filename in files) {
File f = new File(path, filename);
...
}
Oh, I think I see better what you want to do. You want to "reparent" the files:
// Note:
// newParent I assume would be a parameter, not hardcoded
// If so, there is no hardcoding of the platform specific path delimiter
// the value, start, is also assumed to be a parameter
File newParent = new File("C:\\Users\\me\\Desktop\\here");
File[] readFrom = ...;
for (File f in readFrom) {
String[] parts = f.list();
String[] needed = Arrays.copyOfRange(parts, start, parts.length);
File newFile = new File(newParent);
for (String part in needed) {
newFile = new File(newFile, part);
}
...
}
I think you could do something like:
String name = "Rafael";
String lastname = " Nunes";
String fullname = name + lastname;
Here you can see the string concatenation working, and you can often visit the Java documentation.

Pass multiple files to another class

How to pass multiple files to another class?
I am developing an application which first compresses the image and after that it'll convert it into pdf.
The program which i have written works well seperately ie; it compresses the image and then in another project i use the path where the image are stores to convert it to pdf.
Now i want to have both these codes in the same project and i am encountering the problem where i am creating a loop where i pass the path name one by one. The source path works well but i need to specify the destination path which changes the name dynamically this where i am facing the problem. I have attached the code below please tell me what to do.
System.out.println("before convert");
Conversion cc = new Conversion();
File directory = new File(Success);
File[] files = directory.listFiles();
if(files!=null)
{
for(File f:files){
String path = f.getName();
System.out.println("The Name of file is="+path);
cc.createPdf("path" , "output", true);
System.out.println("the file is ="+output+".pdf");
System.out.println("after convert");
}
}
In the above code i need to change the output file name dynamically here cc.createPdf("path" , "output", true);
A simple implementation would be to keep a counter outside loop and increment it before appending it to output file name
int counter = 0;
for(File f:files){
String path = f.getName();
System.out.println("The Name of file is="+path);
counter++; //increment the counter
cc.createPdf("path" , "output"+counter, true); // append it to output
System.out.println("the file is ="+output+".pdf");
System.out.println("after convert");
}
For more robustness, counter can be replaced by UUID generator, System time in milliseconds etc
Im guessing your having trouble getting a File object with a newly created .pdf extension, you will have to adapt this to your code but it should be pretty straight forward.
File inputFile = new File("c:\\myimage.png");
String fileName = inputFile.getName();
File pdfFile = new File(inputFile.getParent(), fileName.substring(0, fileName.indexOf(".")) +".pdf");
System.out.println(inputFile + " " + pdfFile);
I think you should keep things simple by just appending ".pdf" to the names. The fact that you are processing a directory ensures that the source file names are unique. Hence, the new ".pdf" names would also be unique.
Assuming your output files land in the same directory, it also becomes much easier to sort files by names and know immediately which ".pdf" files correlate to which source files.
So, your output file name simply becomes
String path = f.getName();
String output = path.substring(0, path.lastIndexOf('.')) + ".pdf";

Writing to a file without overwriting or appending

I am writing a program in Java where the output is written to a .txt file. Each time I run the program the file is overwritten. I do not want to use the append switch and add data to the file.
I would like to have it so a new file, with the same name, is created each time I run the program. For example, if overflow.txt is the file name, and I run the program three times, the files overflow(1).txt, overflow(2).txt, and overflow(3).txt should be made.
How can this be achieved?
Check if the file exists, if so rename it. Using File.exists and FileUtils.moveFile
You would need to do this recursively until no conflict is found.
Check if the file exists first. If so, modify the name.
String origName = "overflow";
String ext = ".txt";
int num = 1;
file = new File(origName + ext);
while (file.exists()) {
num++;
file = new File(myOrigFileName +"(" + num + ")" + ext);
}
Modify depending on actual requirements. Question is not very clear.
"A new file with the same name" doesn't make sense in most file systems.
In your example, you've got three files with different names:
overflow(1).txt
overflow(2).txt
overflow(3).txt
The bit in brackets is still part of the name. If you want to emulate that behaviour, you'll have to:
Detect the presence of the "plain" filename (if you want to write to that if it doesn't exist)
Start counting at 1, and work out the "new" filename each time by removing the extension, adding the count in brackets, then putting the extension back
Keep counting until you find a filename which doesn't exist
String dirPath = "./";
String fileName = dirPath + "overflow.txt";
if(new File(dirPath + fileName).exist())
{
int counter = 0;
while(new File(dirPath + "overflow(" + ++counter + ").txt").exist());
fileName = "overflow(" + counter + ").txt";
}
When you instanciate the File object, verify if it exists, if it does, just rename it by adding the braces and number, and check again.

Categories