Trouble with ProcessBuilder

吃可爱长大的小学妹 提交于 2019-12-25 09:00:10

问题


Following code opens status very fine in notepad:

import java.util.*;
class test
{
public static void main(String args[])
{
    try{
    ProcessBuilder pb=new ProcessBuilder("notepad","F:/status");
    pb.start();
    }catch(Exception e)
    {
        System.out.println(e);
    }
}
}

Following code does'not play the song:

import java.util.*;
class test
{
public static void main(String args[])
{
    try{
    ProcessBuilder pb=new ProcessBuilder("C:/Program Files (x86)/VideoLAN/VLC/vlc","D:/02 Tu Jaane Na");
    pb.start();
    }catch(Exception e)
    {
        System.out.println(e);
    }
}
}

回答1:


I think that the problem is that you're ignoring the fact that the files you're trying to open have filename extensions.

Windows Explorer doesn't display file extensions by default - that is probably why you are not aware of their existence.

The reason why notepad worked in your first example is that notepad automatically adds .txt extension to its filename parameter in case you didn't provide one yourself. So in reality the file that is being open is not status but status.txt.

VLC doesn't have this "advanced" functionality because there's no specific filename extension it is designed to work with.

So you will need to look up the dir command output and add the full file name as a parameter.

If that was the real issue - you might want to modify your Windows Explorer settings for it to display file extensions:

or, which is better, switch to a more programmer-friendly OS :)




回答2:


For 1.6+ code, use Desktop.open(File) instead.


Of course, the sensible thing to do immediately before calling that is to check File.exists().

OTOH, Desktop.open(File) throws a slew of handy exceptions, including:

  • NullPointerException - if file is null
  • IllegalArgumentException - if the specified file doesn't exist
  • UnsupportedOperationException - if the current platform does not support the Desktop.Action.OPEN action
  • IOException - if the specified file has no associated application or the associated application fails to be launched

Properly handled, the exception would indicate the immediate problem.


As an aside, the Desktop class is designed to be cross-platform, and will handle any file type for which an association is defined. In that sense it is a lot more useful for something like this, than trying to use a Process.



来源:https://stackoverflow.com/questions/9239341/trouble-with-processbuilder

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