0

My program has the following code where output is a StringBuilder:

   try
   {
       BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"));
       bw.write(output.toString());
   }
   catch(IOException e)
   {
       System.out.println("File error: "+e.getMessage());
   }

after the bw.write(output.toString()); I want to have another line that launches the textfile with the default application. I considered using the desktop API but heard it has bad cross-platform compatibility. Any suggestions?

Celeritas
  • 14,489
  • 36
  • 113
  • 194
  • Launch a text file? You mean opening it with the OS specific menu? – tilpner May 21 '14 at 18:42
  • I mean mean opening it with the OS specific applicaon. e.g. notepad – Celeritas May 21 '14 at 18:44
  • Possible duplicate of [Open a file with an external application on Java](http://stackoverflow.com/questions/390736/open-a-file-with-an-external-application-on-java)? – Russell Zahniser May 21 '14 at 18:44
  • So I use desktop api. I haven't had any issues cross-platform. You can't specify the application opening your text file though. Edit: so I looked and it has some problems across different linux environments. Do you need to handle so many edge cases? –  May 21 '14 at 18:45
  • got it working with Desktop api, thanks guys! – Celeritas May 21 '14 at 19:02

2 Answers2

3
File file = new File("somefile.txt");
Desktop desktop = Desktop.getDesktop();
desktop.open(file);

I think you were looking for this.

slaadvak
  • 4,611
  • 1
  • 24
  • 34
Tayyab Hussain
  • 1,658
  • 1
  • 18
  • 21
0
public static void main(String[] args) {
    try {
        Main m = new Main();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public Main() throws IOException {
    File file = new File("test.txt");
    if (!file.exists())
        file.createNewFile();
    Desktop.getDesktop().edit(file);
}

Worked for me

FabianTe
  • 516
  • 4
  • 22