how to find the path of file created using FileOutputStream

Hirad Gorgoroth picture Hirad Gorgoroth · Sep 20, 2015 · Viewed 10k times · Source

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 ?

Answer

Ownaginatious picture Ownaginatious · Sep 20, 2015

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.