call system text editor

﹥>﹥吖頭↗ 提交于 2020-01-04 10:12:34

问题


I have Java desktop application that works with CSV files. And i want add some functionality. At this moment i need to open selected file with default system text editor. When i run my program on Windows i have no problems, just by calling notepad.exe, but what to do with *nix systems? One way of solution is to customly set the way to preffered text editor in program options, but it is not a best solution...

But maybe it would be better add to program own text editor, even with less functionality ?


回答1:


I believe java.awt.Desktop.edit() may be what you're looking for, although it will launch whatever the OS thinks the file should be edited with, which in the case of CSV is usually a spreadsheet app rather than a text editor - maybe you can rename the files to TXT temporarily or permanently.




回答2:


For such functionality, I believe that is much better to use JTextArea and provide your own basic text editor.

Anyway, have a look at the BareBonesBrowserLauncher. It is a Java class that allows you to launch the default browser in any platform. You can adapt it for your needs. Copied from there:

String[] editors = { "vim", "emacs", "vi",};
String editor = null;
for (int count = 0; count < editors.length && editors == null; count++) 
    if (Runtime.getRuntime().exec( new String[] {"which", editors[count]}).waitFor() == 0) 
        editor = editors[count];
if (editor == null) 
    throw new Exception("Could not find editor");
else Runtime.getRuntime().exec(new String[] {editor, filename});



回答3:


Try this:

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class systemEditor {

    public static void main(String[] args) {
        Desktop dt = Desktop.getDesktop();
        try {
            dt.open( new File("FileName.csv") );
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

If the application is for Mac please remember to change the library from default Mac OS 10.5 (JVM 1.5) to JVM 1.6 otherwise java.awt.Desktop would not be resolved.

This does not open text editor though, as Michael Borgwardt, mentioned. It opens MS Excel in my case.

For any more info you can look in java api:

java.awt.Desktop

java.io.File



来源:https://stackoverflow.com/questions/833828/call-system-text-editor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!