how to find the path of file created using FileOutputStream
Asked Answered
P

2

9

I created a file using FileOutputStream and it is an excel file (using HSSF Liberary)

FileOutputStream fileOut = new FileOutputStream(text+".xls");

then I write what I need in my excel file (workbook) and then close the file

workbook.write(fileOut);
fileOut.flush();
fileOut.close();

After closing it I need to display the path of the file to user, (I know that it creates in the folder of my application but I still need to display it to user, maybe via joption/message box)

I tried this :

String absolutePath = fileOut.getAbsolutePath();
JOptionPane.showMessageDialog(null, absolutePath);

but it shows error and it says that it cannot find the method "getAbsolutePath". what should I do ? is there anyway that I can get this path ?

Procurable answered 20/9, 2015 at 8:47 Comment(6)
Have you tried to get fileOut.getAbsolutePath() before closing your fileOut object?Nitrochloroform
new File(text+".xls") then you can use all the properties of File, like getAbsolutePathGleeson
@YassinHH yes , unfortunately it has the same error.Procurable
@YassinHH I'm 99.9% certain that FileOutputStream doesn't have a method caled getAbsolutePath, as determined by the OP's error "cannot find the method"Gleeson
@MadProgrammer, I know it works with file as I used on the other part of my application. However the HSSF library requires to create file using FileOutputStream .Procurable
So? FileOutputStream can also take a File as a reference to write to. FileOuputStream will write to where ever you tell it to, which right now is {user.dir}/{text}.xls (or the current working directory).Gleeson
A
15

You can change your code to use a file instead as an intermediary.

File myFile = new File(text + ".xls");
FileOutputStream fileOut = new FileOutputStream(myFile);

And then just get the path of that:

String absolutePath = myFile.getAbsolutePath();

Make sure to close the stream when you're done:

fileOut.close();

Ideally though, you shouldn't just create the file wherever the Java path happens to be set. You should probably rethink this and instead ask the user where they want to save the file.

Aegeus answered 20/9, 2015 at 8:52 Comment(2)
Thank you so much, It works now. this is the second time you save me with your amazing answers :DProcurable
I added the function of choosing the path to but still I have to display it anyway. thanks againProcurable
I
2

Use new File(text+".xls").getAbsolutePath(). The FileOutputStream doesn't allow accessing the underlying File.

You should get into the habit of reading the javadoc instead of trying random methods. You'll then see what methods exists and what methods don't.

Inchoation answered 20/9, 2015 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.