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 ?

Hirad Gorgoroth
  • 389
  • 2
  • 4
  • 13
  • Have you tried to get fileOut.getAbsolutePath() before closing your fileOut object? – Yassin Hajaj Sep 20 '15 at 08:49
  • 1
    `new File(text+".xls")` then you can use all the properties of `File`, like `getAbsolutePath` – MadProgrammer Sep 20 '15 at 08:50
  • @YassinHH yes , unfortunately it has the same error. – Hirad Gorgoroth Sep 20 '15 at 08:50
  • 2
    @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"* – MadProgrammer Sep 20 '15 at 08:51
  • @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 . – Hirad Gorgoroth Sep 20 '15 at 08:53
  • 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). – MadProgrammer Sep 20 '15 at 08:55

2 Answers2

14

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.

Ownaginatious
  • 787
  • 4
  • 14
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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255