Ini4j not reading file paths - java

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

Related

Put Brackets around filename

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)) + "]";

Reading path files without using extra backslash

I have a .ini file that looks like this and am using ini4j to parse the file:
[Filepath]
Inbound=C:\Users\Bilbo\Desktop\Testing
I want to return that exact string (C:\Users\Bilbo\Desktop\Testing) and I have the following java 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) in the .ini file which returns what im looking for (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 in the .ini flie. Is there a way to read in a string from an .ini file with ini4j or another way around this? Thanks
Easiest way would be to disable escaping.
import org.ini4j.Config;
...
Config.getGlobal().setEscape(false);
Other alternative would be to use the Wini class instead
import org.ini4j.Wini;
...
Wini ini = new Wini(new File(iniFileName));
Just change slash for double slash after reading the file path:
public static String ParseIniInbound (File iniFile) throws
InvalidFileFormatException, IOException {
String iniFileName = iniFile.toString().replaceAll("\\", "\\\\");
Ini ini = new Ini(new File(iniFileName));
String InboundPath= ini.get("Filepath", "Inbound");
return InboundPath;
}

get path of a file in java

My problem is very simple and yet I can't figure out how to solve it.
I have text files in a folder:
"C:/aaa/bbb/ccc/ddd/test.txt"
And excel files in a folder within the text files folder:
"C:/aaa/bbb/ccc/ddd/excelFiles/test.xls"
Both text and excel files have the same name.
I would like to be able to access the path of those excel files.
What I did is:
this.file.getParent()+"\\"+"excelFiles"+"\\"+file.getName().substring(0, fileName.indexOf('.'))+".xls"
I get a "String index out of range" error.
Thank you for your help :)
If I understand your question, one option is to use File.getCanonicalPath() like,
try {
File f = new File("C:/aaa/bbb/ccc/ddd/excelFiles/test.xls");
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
You might want to try this ->
String dynamicExcelFileName = file.getName().substring(0, fileName.indexOf('.'))
into a variable and use it in the path for accessing the excel file.
this way you get to be extra sure to check if the path is properly captured in variable or not and thus less chances of getting index out of range error.
plus the code is more readable
Looking at your snippet, I can see that you're accessing the file's name in two different ways:
file.getName().substring(...)
and
fileName.indexOf(...).
Are you sure that fileName is not empty when you try to determine the index of the dot?
this.file.getParent()+"\"+"excelFiles"+"\"+file.getName().substring(0, this.file.getName().indexOf('.'))+".xls"
This could be achieved quite easily, even without using existing libraries like FileUtils.
These three method can create the corresponding Excel File object for your text object
private File getExcelFile(final File txtFile) throws IOException {
final String path = txtFile.getCanonicalPath();
final String directory = path.substring(0, path.lastIndexOf(System.getProperty("file.separator")));
return new File(getExcelSubdirectory(directory), getExcelFilename(txtFile.getName()));
}
private File getExcelSubdirectory(final String parent) {
return new File(parent, "excelFiles");
}
private static String getExcelFilename(final String filename) {
return filename.substring(0, filename.lastIndexOf('.')) + ".xls";
}
If you use them like this:
File txt = new File("C:/aaa/bbb/ccc/ddd/test.txt");
System.out.println(txt.getCanonicalPath());
File excel = getExcelFile(txt);
System.out.println(excel.getCanonicalPath());
.. it will print:
C:\aaa\bbb\ccc\ddd\test.txt
C:\aaa\bbb\ccc\ddd\excelFiles\test.xls

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.

Java cannot find a file existing on the server

In my Java Spring web app I am creating an image file. This file gets a temporary name and later on I try to rename it using:
public void rename(String productFilename){
String newProductFilename = "newfile.jpg";
File input = new File(imageDir + "/products/" + productFilename);
File output = new File(imageDir + "/products/" + newProductFilename);
Boolean checkRename = input.renameTo(output);
}
For creating the temp file, I'm using:
public String generate(){
String productFilename = "filename.jpg";
ImageIO.write(out, imageFileType, new File(imageDir + "/products/" + productFilename));
return productFilename;
}
the value of imageDir is: /var/images
Throughout the class, the imageDir variable is set to an absolute path. The strange thing is that this all works great on Windows, but when running on Linux, I get a FileNotFoundException.
I'm 100% sure that the file exists. Any clue on what I'm doing wrong?
I found the solution. The filenames needed to be trimmed to be recognised in Linux. This, however, worked without trimming in Windows.

Categories